思路:
由题意可知最多有2个数出现的次数超过1/3,分别计算他们出现的次数,方法类似 Majority Element
。
时间复杂度:O(N),空间复杂度:O(1)。
java code:
public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> ans = new ArrayList<Integer>();
if(nums == null || nums.length == 0) return ans;
if(nums.length == 1) {
ans.add(nums[0]);
return ans;
}
int candidate1 = nums[0], count1 = 1;
int candidate2 = 0, count2 = 0;
for(int i = 1; i < nums.length; ++i) {
if(nums[i] == candidate1) {
++count1;
}else if(nums[i] == candidate2) {
++count2;
}else if(count1 == 0) {
candidate1 = nums[i];
count1 = 1;
}else if(count2 == 0) {
candidate2 =nums[i];
count2 = 1;
}else {
--count1;
--count2;
}
}
count1 = 0;
count2 = 0;
for(int i = 0; i < nums.length; ++i) {
if(nums[i] == candidate1) ++count1;
else if(nums[i] == candidate2) ++count2;
}
if(count1 > nums.length / 3) ans.add(candidate1);
if(count2 > nums.length / 3) ans.add(candidate2);
return ans;
}
}