[Java][Leetcode simple] 169. 多数元素

哈希表暴力枚举

    public int majorityElement(int[] nums) {

        int res = 0;
        Map<Integer, Integer> map = new HashMap<>();
        int len = nums.length;
        for (int j : nums) {
            if (map.containsKey(j)) {
                map.put(j, map.get(j) + 1);
            } else {
                map.put(j, 1);
            }
        }
        res = map.keySet().stream().filter(num -> map.get(num) > len / 2).findFirst().orElse(0);

        return  res;
    }

摩尔投票

通过元素抵消的方式找到最终候选人

public int majorityElement2(int[] nums) {
        int count = 0;
        int candidate = 0;

        for(int j: nums){
            if(count == 0){
                candidate = j;
            }
            if(j == candidate){
                count++;
            }else {
                count--;
            }
        }

        return candidate;
    }

你可能感兴趣的:(#,[Java]力扣面试常见150,java,leetcode)