169. 多数元素

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

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

示例 1:

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

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

解法一:哈希表

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

                hash.put(nums[i], hash.get(nums[i]) + 1);
            }
            int temp = hash.get(nums[i]);
            if (temp > len / 2)
                return nums[i];
        }
        return 0;

    }

解法二:Boyer-Moore 投票算法   大混战

public int majorityElement(int[] nums) {
        int cnt = nums[0];
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (count == 0) {
                cnt = nums[i];
                count = 1;
            } else {
                count += (cnt == nums[i]) ? 1 : -1;
            }
        }
        return count;

    }
原文地址:https://www.cnblogs.com/xiaoming521/p/14883255.html