229. 求众数 II
169. 多数元素的升级版
class Solution {
public List<Integer> majorityElement(int[] nums) {
// 先用投票法,找出两个候选人; 再遍历这两个候选人出现的次数是不是符合要求
if (nums == null || nums.length == 0) {
return new ArrayList<Integer>();
}
int n1 = nums[0], n2 = nums[0];
int times1 = 0, times2 = 0;
for (int a : nums) {
if (a == n1) { // 给n1投票
times1++;
continue;
}
if (a == n2) { // 给n2投票
times2++;
continue;
}
if (times1 == 0) { // 都不投票,如果n1现在0票,则替换n1
n1 = a;
times1 = 1;
continue;
}
if (times2 == 0) { // 都不投票,如果n1现在0票,则替换n1
n2 = a;
times2 = 1;
continue;
}
// n1和n2都大于0票,则都减一票
times1--;
times2--;
}
times1 = times2 = 0;
for (int a : nums) {
if (a == n1) {
times1++;
} else if (a == n2) { // else if: 保证n1==n2时,只返回一个结果
times2++;
}
}
List<Integer> res = new ArrayList<>();
if (times1 > nums.length/3) {
res.add(n1);
}
if (times2 > nums.length/3) {
res.add(n2);
}
return res;
}
}