LeetCode[169] Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

投票法

复杂度
O(N),O(1)

思路
设定一个candidate,和这个candidate对应的count.如果一个数和这个candidate相等,那么就将count增加,否则减少count的数目。

代码

public int majorityElement(int[] nums) {
    if(nums == null || nums.length == 0) return 0;
    int candidate = 0;
    int cnt = 0;
    for(int num : nums) {
        if(num == candidate) {
            cnt ++;
        }
        else if(cnt == 0) {
            candidate = num;
        }
        else {
            cnt --;
        }
    }
    return candidate;
}

hellolittleJ17
10 声望11 粉丝