# 摩尔投票算法( Boyer-Moore Voting Algorithm)

1. 遍历每一个元素，并计数
2. 排序法

1.定义两个变量：m存储当前变量到的元素，count为计数器，初始情况下，count=0；

2.依次遍历数组中的每个元素，当遍历到元素x时，

3.处理完后，最后m存储的值就是这个序列中最多的元素；

int MajorityVote(vector<int> nums) {
int res = 0, cnt = 0;
for (auto &num : nums) {
if (cnt == 0) {
res = num;
cnt++;
}
else if (num == res)cnt++;
else cnt--;
}
return res;
}


1，题目： LeetCode 229 [Majority Element II]

### C++代码

class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> re;
if (nums.size()==0) return re;
int candidate1 = 0;
int count1 = 0;
int candidate2 = 0;
int count2 = 0;
for (int i=0; i<nums.size(); i++) {
if (nums[i] == nums[candidate1]) count1++;
else if (nums[i] == nums[candidate2]) count2++;
else if (count1==0) {
candidate1 = i;
count1 = 1;
}
else if (count2==0) {
candidate2 = i;
count2 = 1;
}
else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for (int i=0; i<nums.size(); i++) {
if (nums[i] == nums[candidate1]) count1++;
else if (nums[i] == nums[candidate2]) count2++;
}
if (count1 > nums.size()/3) re.push_back(nums[candidate1]);
if (count2 > nums.size()/3) re.push_back(nums[candidate2]);
return re;
}
};

posted @ 2020-03-13 14:22  RioTian  阅读(...)  评论(...编辑  收藏