Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
解答:
其实就是求众数,可以推测出,大于三分之一的众数是顶多只有两个的。那么遇见一个数就加一,遇见不是的就减一。假如减到零,就置为一。最后还要判断一下这个众数满不满足条件。
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> res;
int cntm=0,cntn=0,m=0,n=0;
for(auto a:nums)
{
if(a==m) cntm++;
else if (a==n) cntn++;
else if (cntm==0){ m=a;cntm++;}
else if (cntn==0){ n=a;cntn++;}
else {cntm--;cntn--;}
}
cntm=0,cntn=0;
for(auto a:nums)
{
if(a==m) cntm++;
else if(a==n) cntn++;
}
if(cntm>nums.size()/3) res.push_back(m);
if(cntn>nums.size()/3) res.push_back(n);
return res;
}
};