力扣229. 求众数 II(hashmap/摩尔投票法)

229. 求众数 II - 力扣(LeetCode) (leetcode-cn.com)

 hashmap

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        HashMap<Integer,Integer> hashmap = new HashMap<>();
        int n = nums.length;
        int num = n/3;
        for (int i:nums){
            hashmap.put(i,hashmap.getOrDefault(i,0)+1);
        }
        List<Integer> res = new ArrayList<>();
        for(int i:hashmap.keySet()){
            if(hashmap.get(i)>num){
                res.add(i);
            }
        }
        return res;
    }
}

 摩尔投票法

两幅动画演示摩尔投票法,最直观的理解方式 - 求众数 II - 力扣(LeetCode) (leetcode-cn.com)

public class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums.length==0)return res;
        int sel1 = nums[0];
        int sel2 = nums[0];
        int count1 = 0;
        int count2 = 0;
        for(int num:nums){
            if(sel1==num){
                count1++;
                continue;
            }
            if(sel2==num){
                count2++;
                continue;
            }
            if(count1==0){//注意是当前投票数减到0后,下一个投票如果还不为当前投票进行更换
                sel1 = num;
                count1++;
                continue;
            }
            if(count2==0){//注意是当前投票数减到0后,下一个投票如果还不为当前投票进行更换
                sel2 = num;
                count2++;
                continue;
            }
            count1--;
            count2--;
        }
        count1 = 0;
        count2 = 0;
        for (int num : nums) {
            if (sel1 == num) count1++;
            else if (sel2 == num) count2++;
        }
        if (count1 > nums.length / 3) res.add(sel1);
        if (count2 > nums.length / 3) res.add(sel2);
        return res;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值