Leetcode_229_求众数2_摩尔投票法

方法是真的巧妙,首先我们可以确定超过总数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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值