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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Divide and Conquer Array Bit Manipulation
出现的次数比一般还多,用一个candidate记录是不是这个数,出现次数+1,不是出现-1
当count为0时替换candidate
class Solution {
public:
int majorityElement(vector<int>& nums) {
int candidate=0;
int count=0;
for(auto it=nums.begin();it!=nums.end();it++){
if(count==0){
candidate=*it;
count++;
continue;
}
else{
if(candidate==*it){
count++;
}
else{
count--;
}
}
}
return candidate;
}
};