Boyer-Moore Voting Algorithm 多数投票算法

##Majority Element题目介绍:给定一个长度为n的数组的时候,找出其中的主元素,即该元素在数组中出现的次数大于n/2的取整。题目中已经假定所给的数组一定含有元素,且主元素一定存在。

在刷leetcode 169. Majority Element 的时候发觉这个算法相当巧妙,hash表的找主成分方法时间复杂度是O(nlogn);而这个方法是只需要遍历一次的O(n)。

这个算法利用的关键在于,题目给定的数组必有主元素,主元素占大于1/2。
所以我们只需要将不同的数字两两相消,消剩下的就肯定是大于1/2了。

##这是作者本人做的例子
http://www.cs.utexas.edu/~moore/best-ideas/mjrty/example.html#step13

##这是我的代码

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size(),count=0,cdd;
        for(int i=0;i<n;i++){
            if(count==0) cdd=nums[i];
            nums[i]==cdd? count++:count--;
            //用到count是统计相同的数字,当数字与candidate不同时,count--也就是相消了

        }
       return cdd;
    }
};
收藏 打印