Leetcode(Java)-169. 多数元素

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

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

示例 1:

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

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

思路1:Hashmap 存储 <数字,数字出现的次数>

class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer,Integer> count=new HashMap<>();
        for(int i=0;i<nums.length;i++){
            if(!count.containsKey(nums[i]))
                count.put(nums[i],1);
            else{
                count.put(nums[i],count.get(nums[i])+1);
            }
        }

        for(Integer k:count.keySet()){
            if(count.get(k)>nums.length/2)
                return k;
        }
        return 0;
    }
}

思路2:Boyer-Moore 投票算法

想法

如果我们把众数记为 +1 ,把其他数记为 −1 ,将它们全部加起来,显然和大于 0 ,从结果本身我们可以看出众数比其他数多。

class Solution {
    public int majorityElement(int[] nums) {
        int count = 0;
        Integer candidate = null;

        for (int num : nums) {
            if (count == 0) {
                candidate = num;
            }
            count += (num == candidate) ? 1 : -1;
        }

        return candidate;
    }
}

发布了149 篇原创文章 · 获赞 31 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_38905818/article/details/104077308