leetcode 169. Majority Element 多数投票算法(Boyer-Moore Majority Vote algorithm)

题目:

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.

题解:运用多数投票算法的思路来解:从头到尾遍历数组,遇到两个不一样的数就把这两个数同时除去。除去的两个数可能都不是majority,也可能一个是majority一个不是,但是因为majority总数大于一半(注意不能等于一半),所以这么删完了最后肯定剩下的数是majority。(因为题目说了肯定有majority,如果没说,剩下的那个数未必是majority,还应该遍历一遍数组统计这个数的出现次数)。

这个算法的时间复杂度O(n),空间复杂度O(1)

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int cnt=0,ans=0;
        for(auto a:nums){
            if(cnt==0){
                ans=a;
                cnt=1;
            }
            else if(a==ans){
                cnt++;
            }
            else{
                cnt--;
            }
        }
        return ans;
    }
};

扩展:如果找改成大于[n/3]的,道理完全一样。参见这道题

posted @ 2016-04-16 22:14  周洋  阅读(1089)  评论(0编辑  收藏  举报