leetcode-169-easy

Majority Element

思路一: map

public int majorityElement(int[] nums) {
    if (nums.length == 1) return nums[0];

    Map<Integer, Integer> map = new HashMap<>();
    int N = nums.length / 2;
    for (int num : nums) {
        if (map.containsKey(num)) {
            Integer n = map.get(num);
            if (n + 1 > N) {
                return num;
            }
            map.put(num, n + 1);
        } else {
            map.put(num, 1);
        }
    }

    throw new RuntimeException("error");
}

思路二: 排序,中间的数字一定是求解,用反证法可以证明。这个思路一开始没有想到

思路三: 随机取一个数,然后验证。这种思路也很巧妙,但是复杂度不好控制,运气不好可能要跑很长时间

思路四: 分治法,把数组分为两半,其中一边的值必然有 Majority Element,用反证法可以证明。这样复杂问题就可以越分越小,分治法的思想很巧妙

思路五: Boyer-Moore 投票算法

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;
}
posted @ 2022-10-22 22:20  iyiluo  阅读(23)  评论(0)    收藏  举报