题目: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.
思路:
在Majority Element中,了解了Moore Voting算法。该题延续该算法,并进行改进。
如果只有一个majority,我们只需要维护一个candidate和count就行。nums[i]==candidate,count++ ;nums[i]!=candidate,count-- ; 最后candidate即为majority。
但是本题中,majority 个数大于 n/3 ,所以可能是两个,所以,维护两个candidate以及count。
(tips:用这个算法可以通过调整candidate的个数,得到nums中个数最多的数。)
通过Moore Voting得到了个数最多的两个数,仍要进行筛选,判断个数是不是大于n/3。nums[i]==candidate,count+=2; nums[i]!=candidate,count--;如果最后count>0,则是超过n/3的majority。
代码:
public List<Integer> majorityElement(int[] nums) {
List<Integer> rst = new ArrayList<Integer>();
if(nums == null || nums.length == 0) return rst;
int count1 = 0, count2 = 0, candidate1 = 0, candidate2 = 1;
for(int num : nums){
if(num == candidate1) count1++;
else if(num == candidate2) count2++;
else if(count1 == 0){
candidate1 = num;
count1 = 1;
}
else if(count2 == 0){
candidate2 = num;
count2 = 1;
}
else{
count1--;
count2--;
}
}
count1 = 0; count2 = 0;
for(int num : nums){
if(num == candidate1) count1+=2;
else count1--;
if(num == candidate2) count2 += 2;
else count2--;
}
if(count1 > 0) rst.add(candidate1);
if(count2 > 0) rst.add(candidate2);
return rst;
}