类似消消乐游戏,每次取一部分元素匹配,剩下的没有匹配的,即为超过半数元素的值
class Solution {
public:
int majorityElement(vector<int>& nums) {
size_t length = nums.size();
int tag = nums[0];
int i = 0;
int count = 1;
while (i+1<length) {
if (tag!=nums[i+1]) {
count--;
} else {
count++;
}
if (count==0&&(i+2)<length) {
tag = nums[i+2];
i+=2;
count = 1;
} else {
i++;
}
}
return tag;
}
};