229. 求众数 II

  1. 求众数 II
    给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。
示例 1:
输入:[3,2,3]
输出:[3]
示例 2:
输入:nums = [1]
输出:[1]
示例 3:
输入:[1,1,1,3,3,2,2,2]
输出:[1,2]

//方法一:哈希表计数
    public List<Integer> majorityElement(int[] nums) {
        HashMap<Integer,Integer>ans=new HashMap<Integer,Integer>();
        List<Integer>ret=new ArrayList<>();
        for(int i=0;i<nums.length;i++)
        {
            ans.put(nums[i],ans.getOrDefault(nums[i],0)+1);
        }
        int n=nums.length;
        for(Map.Entry<Integer,Integer>entry: ans.entrySet())
        {
            int num=entry.getKey(),occ=entry.getValue();
            if(occ>=n/3)
              ret.add(new Integer(num));
        }
        return ret;
    }
    //摩尔投票法,时间复杂度为O(1)
    public List<Integer> majorityElement1(int[] nums)
    {
        List<Integer>res=new ArrayList<>();
        if(nums==null||nums.length==0)
            return res;
        //初始化候选人,以及计票
        int cand1=nums[0],count1=0;
        int cand2=nums[0],count2=0;
        //摩尔投票
        for(int num:nums)
        {
            if(cand1==num)
            {
                count1++;
                continue;
            }
            if(cand2==num)
            {
                count2++;
                continue;
            }
            if(count1==0)
            {
                cand1=num;
                count1++;
                continue;
            }
            if(count2==0)
            {
                cand2=num;
                count2++;
                continue;
            }
            count1--;
            count2--;
        }
        count1=0;
        count2=0;
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i]==cand1)
                count1++;
            if(nums[i]==count2)
                count2++;
            //if(co)
        }
        if(count1>nums.length/3)
            res.add(cand1);
        if(count2>nums.length/3)
            res.add(cand2);
        return res;
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值