0堆中等 LeetCode347. 前 K 个高频元素

347. 前 K 个高频元素

描述

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

分析

使用map集合统计每个数字的出现次数,利用小顶堆计算出前k大热频数字。
推荐代码一思路
代码一与代码二的区别在于,小顶堆存储的数据类型。
代码一存储的是map集合的key,代码二存储的是map集合的entry。比较器都是比较map的value。代码一至多一只需要存储map的key,得益于比较器。
代码一的数据类型是Integer,代码二存储的是Map.Entry<Integer,Integer>,书写困难,容易出错。
代码一利用了lambok特性,书写简单。

代码一
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i : nums){
            if(map.containsKey(i)){
                int tmp = map.get(i)+1;
                map.put(i,tmp);
            }else{
                map.put(i,1);
            }
        }

        PriorityQueue<Integer> heap = new PriorityQueue<>( (a,b)->(map.get(a) - map.get(b)));
        for(Integer num : map.keySet()){
            heap.add(num);
            if(heap.size()>k){
                heap.poll();
            }
        }

        int[] res = new int[k];
        for(int i = 0; i < k; i++){
            res[i] = heap.poll();
        }
        return res;
    }
}
代码二
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i : nums){
            if(map.containsKey(i)){
                int tmp = map.get(i)+1;
                map.put(i,tmp);
            }else{
                map.put(i,1);
            }
        }

        PriorityQueue<Map.Entry<Integer,Integer>> heap = new PriorityQueue<>(k,new Comparator<Map.Entry<Integer,Integer>>(){
            public int compare(Map.Entry<Integer,Integer> m1, Map.Entry<Integer,Integer> m2){
                return m1.getValue() - m2.getValue();
            }
        });
        for(Map.Entry<Integer,Integer> entry : map.entrySet()){
            heap.add(entry);
            if(heap.size() > k){
                heap.poll();
            }
        }

        int[] res = new int[k];
        for(int i = 0; i < k; i++){
            res[i] = heap.poll().getKey();
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值