169. 多数元素

136 阅读1分钟

方法一:排序取中点 O(NlogN)

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }
}

方法二:摩尔投票法 O(N) O(1)

image.png

class Solution {
    public int majorityElement(int[] nums) {
        int candidate = nums[0];
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == candidate) {
                count++;
            } else {
                count--;
                if (count == 0) {
                    candidate = nums[i]; // 换
                    count = 1;
                }
            }
        }
        return candidate;
    }
}

方法三:topK O(N)