// 20181028
// cross training 6
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int majorityElement(vector<int>& nums) {
if (nums.size() == 1){
return nums[0];
}
vector<int> holder(2); // size is two : key, value
holder[0] = nums[0];
holder[1] = 1;
for (std::vector<int>::iterator it= ++nums.begin(); it != nums.end(); it++) {
if (holder[1] == 0) {
holder[0] = *it; // the stage is empty
holder[1]++;
}
else if (*it == holder[0])
holder[1]++;
else
holder[1]--;
}
return holder[0];
}
};
int main() {
vector<int> test = {10,9,9,9,10};
Solution s;
int res = s.majorityElement(test);
std::cout << res << std::endl;
return 0;
}
Boyer–Moore majority vote algorithm
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.