多数元素

题目:

给定一个大小为 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;
    }
}

 

posted @ 2020-07-16 13:49  无心大魔王  阅读(145)  评论(0编辑  收藏  举报