169. Majority Element

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.

常规办法: 使用 map<int, int> hash; 然后顺序扫描并投票. 这办法 robust, but (O(n)) time, (O(n/2)) space, bcz hash.

这题前提很重要,就是 the majority element always exist. 否则下解出错,如 3 3 5 6 7, 会 return 7.

重点是下面精巧的逻辑:

初始值 major = A[0], count = 1;
从i = 1开始扫数组:
若count==0, count++; major = A[i];
否则若有相等的, count++;
否则(就是不等,且count未归0,那就count-1) count--;

(O(n)) time, (O(1)) extra space
人家牛逼代码 without hash:

int majorityElement(vector<int>& A) {
    int major = A[0], count = 1;
    // 只判断一半是不行的,如 1 2 2 || 3 3 3
    for (int i = 1; i < A.size(); i++) {
        if (count == 0) {
            count++;
            major = A[i];
        } else if (major == A[i]) count++;
        else count--;
    }
    return major;
}
原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7357019.html