每日一题 LeetCode 229. 求众数 II java题解

【摩尔投票】

题目

在这里插入图片描述

分析

存在一个这样的数

有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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值