【摩尔投票】
题目
分析
存在一个这样的数
有k个数x,出现次数大于n/3;剩下的有n-k个数,出现次数 不大于n/3。剩下的这些数按三个一组分,就有(n-k)/3 组。
存在两个这样的数
分为三部分。
第一部分:m个x
第二部分:n个y
第三部分:(n-m-n)/3 组,三个互不相同的元素
不会存在三个这样的数
操作
有两个选中数a和b。
每次检测当前数 是否为 a 或 b。
如果都不是,那么进行抵消一次。
如果存在最终选票大于0的数,我们需要看他票数是否大于n/3。
代码
写了一个世纪
class Solution {
public List<Integer> majorityElement(int[] nums) {
int n=nums.length;
List<Integer> res=new ArrayList<>();
if(n==1){
res.add(nums[0]);
return res;
}
int a=Integer.MAX_VALUE;
int b=Integer.MAX_VALUE;
int counta=0;
int countb=0;
for(int i=0;i<n;i++){
if(counta>0&&nums[i]==a){
counta++;
}
else if(countb>0&&nums[i]==b){
countb++;
}
else if(counta<=0){
a=nums[i];
counta++;
}
else if(countb<=0){
b=nums[i];
countb++;
}
else{
counta--;
countb--;
}
}
//验证a、b出现次数是否大于n/3
int c1=0,c2=0;
for(int i=0;i<n;i++){
if(counta>0&&a==nums[i]){
c1++;
}
if(countb>0&&b==nums[i]){
c2++;
}
}
if(counta>0&&c1>n/3){
res.add(a);
}
if(countb>0&&c2>n/3){
res.add(b);
}
return res;
}
}