public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
int candidate1 = 0;
int candidate2 = 1;
int times1 = 0;
int times2 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == candidate1) {
times1 += 1;
} else if (nums[i] == candidate2) {
times2 += 1;
} else if (times1 == 0) {
times1 += 1;
candidate1 = nums[i];
} else if (times2 == 0) {
times2 += 1;
candidate2 = nums[i];
} else {
times1 -= 1;
times2 -= 1;
}
}
times1 = 0;
times2 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == candidate1) times1 += 1;
if (nums[i] == candidate2) times2 += 1;
}
if (times1 > nums.length / 3) res.add(candidate1);
if (times2 > nums.length / 3) res.add(candidate2);
return res;
}