AcWing 52. 数组中出现次数超过一半的数字
原题链接
中等
作者:
哈哈哈hh
,
2020-06-27 17:53:21
,
所有人可见
,
阅读 416
O(1) 时间复杂度
class Solution {
public:
int moreThanHalfNum_Solution(vector<int>& nums) {
if(nums.size() == 0)
return 0;
int curTimes = 0;
int curValue = nums[0];
for(int i = 1; i < nums.size(); i++)
{
if(curValue == nums[i])
{
curTimes++;
}
else
{
curTimes--;
}
if(curTimes < 0)
{
curValue = nums[i];
curTimes = 1;
}
}
curTimes = 0;
for(int i = 0; i < nums.size(); i++)
{
if(nums[i] == curValue)
{
curTimes++;
}
}
if(curTimes >= nums.size()/2)
return curValue;
else
return 0;
}
};