229. Majority Element II
2017-09-26 本文已影响0人
namelessEcho
思路就是三个三个删,如何描述是三个三个删的关键是两个count要描述好。之前没仔细写,count应该有四种case 都要注意。
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> result = new ArrayList<>();
if(nums==null||nums.length==0) return result;
int target1 = nums[0];
int target2 = 0;
for(int i = 0 ;i<nums.length;i++ )
{
if(nums[i]!=target1)
{
target2=nums[i];
break;
}
}
int count1= 0;
int count2= 0;
for(int i = 0;i<nums.length;i++ )
{
if(nums[i]==target1)
count1++;
else if(nums[i]==target2)
count2++;
else
{
if(count1==0&&count2==0)
{
target1=nums[i];
count1++;
}
else if(count1!=0&&count2==0)
{
target2=nums[i];
count2++;
}
else if(count1==0&&count2!=0)
{
target1=nums[i];
count1++;
}
else
{
count2--;
count1--;
}
}
}
count1= 0;
count2= 0;
for(int i = 0;i<nums.length;i++ )
{
if(nums[i]==target1)
count1++;
if(nums[i]==target2)
count2++;
}
if(count1>nums.length/3)
result.add(target1);
if(count2>nums.length/3)
{
if(target1!=target2)
result.add(target2);
}
return result;
}
}