方法是真的巧妙,首先我们可以确定超过总数n/3的数最多有两个,接着我们设置一个抵消策略:
如果num1和num2目前没有数,那么我们将数放入其中,并将count1或count2设置为1;
接着,如果这个数和num1或者num2相同,将count1或count2++;
如果都不一样,将count1和count2–;
这里要注意先判断count1++和count2++,不然如果num1被取消了,num2还有,这时候来一个num2,会使得num1 == num2,使得计算结果出错
如此抵消下来,如果确实存在这两个数,最后剩下来的就是答案。所以最后再校验一下即可。
class Solution {
public List<Integer> majorityElement(int[] nums) {
int n = nums.length;
int a = 0, b = 0;
int c1 = 0, c2 = 0;
for (int i : nums) {
if (c1 != 0 && a == i) c1++;
else if (c2 != 0 && b == i) c2++;
else if (c1 == 0) {a = i;c1++;}
else if (c2 == 0) {b = i;c2++;}
else {
c1--; c2--;
}
}
c1 = 0; c2 = 0;
for (int i : nums) {
if (a == i) c1++;
else if (b == i) c2++;
}
List<Integer> ans = new ArrayList<>();
if (c1 > n / 3) ans.add(a);
if (c2 > n / 3) ans.add(b);
return ans;
}
}