题目来源:https://leetcode-cn.com/problems/majority-element/
class Solution {
public List<Integer> majorityElement(int[] nums) {
if(nums == null||nums.length == 0){
return new ArrayList();
}
int res1 = nums[0];
int res2 = nums[0];
int count1 = 0;
int count2 = 0;
int n = nums.length;
ArrayList<Integer> ans = new ArrayList();
for(int i = 0;i<nums.length;i++){
if(nums[i] == res1){
count1++;
continue;
}
if(nums[i] == res2){
count2++;
continue;
}
if(count1 == 0){
res1 = nums[i];
count1 = 1;
continue;
}
if(count2 == 0){
res2 = nums[i];
count2 = 1;
continue;
}
count1--;
count2--;
}
count1 = 0;
count2 = 0;
for(int num:nums){
if(num==res1){
count1++;
}else if(num==res2){
count2++;
}
}
if(count1>n/3){
ans.add(res1);
}
if(res2!=res1&&count2>n/3){
ans.add(res2);
}
return ans;
}
}