Spurs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
}
posted on 2017-08-14 11:56  英雄与侠义的化身  阅读(97)  评论(0编辑  收藏  举报