目录
牛客_JZ39数组中出现次数超过一半的数字
解析代码
之前博客写过了,摩尔投票法:
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
int cnt = 0 , ret = 0;
for(int i = 0; i < numbers.size(); ++i)
{
if(cnt == 0)
{
ret = numbers[i];
cnt++;
}
else
{
ret == numbers[i] ? ++cnt : --cnt;
}
}
return ret;
}
};