【LeetCode】229. Majority Element II

时间:2022-05-01 19:55:48

Majority Element II

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.

Hint:

  1. How many majority elements could it possibly have?
  2. Do you have a better hint? Suggest it!

超过⌊ n/k ⌋ 最多有(k-1)个结果。k=3时最多2个结果。

因此设置两个candidate进行判断。

注意:留到最后的candidate不代表真正的结果。举例[3,2,3],2是candidate但不是结果。

class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> ret;
if(nums.empty())
return ret;
int candidate1 = nums[];
int count1 = ;
int candidate2 = nums[];
int count2 = ;
for(int i = ; i < nums.size(); i ++)
{
if(count1 != && count2 != )
{
if(nums[i] == candidate1)
count1 ++;
else if(nums[i] == candidate2)
count2 ++;
else
{
count1 --;
count2 --;
}
}
else if(count1 != && count2 == )
{
if(nums[i] == candidate1)
count1 ++;
else
{
candidate2 = nums[i];
count2 = ;
}
}
else if(count1 == && count2 != )
{
if(nums[i] == candidate2)
count2 ++;
else
{
candidate1 = nums[i];
count1 = ;
}
}
else
{
candidate1 = nums[i];
count1 = ;
}
}
if(count1 != )
{
count1 = ;
for(int i = ; i < nums.size(); i ++)
{
if(nums[i] == candidate1)
count1 ++;
}
if(count1 > nums.size()/)
ret.push_back(candidate1);
}
if(count2 != )
{
count2 = ;
for(int i = ; i < nums.size(); i ++)
{
if(nums[i] == candidate2)
count2 ++;
}
if(count2 > nums.size()/)
ret.push_back(candidate2);
}
return ret;
}
};

【LeetCode】229. Majority Element II