思路:count计数,重复时累计加1;不重复时,减1;当count为0时,当前值cur为下以元素
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int times = 0;
int cur = 0;
for(unsigned int i=0; i<numbers.size(); i++)
{
if(times == 0)
{
cur = numbers[i];
times++;
}
else if(numbers[i] == cur)
{
times++;
}
else
{
times--;
}
}
times = 0;
for(unsigned int i=0; i<numbers.size(); i++)
{
if(cur == numbers[i])
{
times++;
}
}
return (times > (numbers.size()/2)) ? cur : 0;
}
};