首页 > 其他 > 详细

多数元素

时间:2020-07-16 15:39:19      阅读:37      评论:0      收藏:0      [点我收藏+]

题目:

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

 

示例 1:

输入: [3,2,3]
输出: 3

示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

分析:

这道题目让我想到了可以排序后,再统计个数,或者利用hashmap中key唯一的特性,遍历数组存入hashmap,键为数组元素本身,值为出现的次数,然后选出其中满足条件的多数元素即可。略微纠结了一下,然后果断尝试了第二种想法,做完之后,看了一下别人的答案,果然还是我太年轻,又是日常羡慕别人的思路中。按照惯例,先记录一下自己的代码,以后再慢慢研究更优化的解法。

代码:

class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        Integer cache = null;
        for (int i : nums) {
            cache = map.get(i);
            if (cache == null) {
                map.put(i, 1);
            } else {
                map.put(i, cache + 1);
            }
        }
        cache = 0;
        for (int i : map.keySet()) {
            int j = map.get(i);
            if (cache < j && j > nums.length / 2) {
                cache = i;
            }
        }
        return cache;
    }
}

 

多数元素

原文:https://www.cnblogs.com/wxdmw/p/13322254.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!