class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
int maj1 = Integer.MIN_VALUE, maj2 = Integer.MIN_VALUE;
int count1 = 0, count2 = 0;
for (int num : nums) {
if (num == maj1) count1++;
else if (num == maj2) count2++;
else if (count1 == 0) {
maj1 = num;
count1++;
}
else if (count2 == 0) {
maj2 = num;
count2++;
}
else {
count1--;
count2--;
}
}
// scan the input array one more time to check if maj1 or maj2 is the result
count1 = 0;
count2 = 0;
for (int num : nums) {
if (num == maj1) count1++;
else if (num == maj2) count2++;
}
if (count1 > nums.length / 3.0) res.add(maj1);
if (maj1 != maj2) {
if (count2 > nums.length / 3.0) res.add(maj2);
}
return res;
}
}