原题链接:https://leetcode.com/problems/majority-element-ii/
题目描述:题目要求找出一个数是在一个数组中出现大于n/3次的。
思路:这道题要求用O(1)space来做,我么就不能用hashmap来。所以我们来思考Majority Element,https://leetcode.com/problems/majority-element/是怎么做的。首先我们确定一个数,设置一个计数器,如果遇到数和预先的数相等,计数器加一,不等,计数器减一。当计数器为0时,重新选择特定数。这道题也是一样,Majority 数如果是超过n/3次的话,则说明最多只有2个这样的数。我们把这两个数合在一起来计数。思路完全一样。代码如下:
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
if(nums.length == 0)
return res;
int a = Integer.MIN_VALUE;
int counta = 0;
int b = Integer.MIN_VALUE;
int countb = 0;
for(int i = 0;i<nums.length;i++)
{
if(counta == 0 )
{
a = nums[i];
}
else if(countb == 0)
{
b = nums[i];
}
if(nums[i] == a)
{
counta++;
}
else if(nums[i] == b)
{
countb++;
}
else
{
counta--;
countb--;
}
}
counta = 0;
countb = 0;
for(int i = 0;i<nums.length;i++)
{
if(nums[i] == a)
{
counta++;
}
if(nums[i] == b)
{
countb++;
}
}
int k = nums.length/3;
if(counta>k)
{
res.add(a);
}
if(countb>k && a!=b)
{
res.add(b);
}
return res;
}