LeetCode 热题100-82-前K个高频元素

核心思想:优先队列+HashMap
思路:
首先遍历整个数组,并使用哈希表记录每个数字出现的次数,并形成一个「出现次数数组」。

在这里,我们可以利用堆的思想:建立一个小顶堆,然后遍历「出现次数数组」:

如果堆的元素个数小 k,就可以直接插入堆中。
如果堆的元素个数等于 k,则检查堆顶与当前出现次数的大小。如果堆顶更大,说明至少有 k 个数字的出现次数比当前值大,故舍弃当前值;否则,就弹出堆顶,并将当前值插入堆中。
遍历完成后,堆中的元素就代表了「出现次数数组」中前 k 大的值。

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> hashmap = new HashMap<>();
        for(int num : nums){
            int count = hashmap.getOrDefault(num, 0);
            hashmap.put(num, count + 1);
        }
        Set set = hashmap.keySet();
        //小根堆
        Queue<int[]> priorityQueue = new PriorityQueue<>(new Comparator<int[]>(){
            public int compare(int[] m, int[] n){
                return m[1] - n[1];
            }
        });
        for(Map.Entry<Integer, Integer> entry : hashmap.entrySet()){
            int num = entry.getKey();
            int count = entry.getValue();
            if(priorityQueue.size() == k){
                if(priorityQueue.peek()[1] < count){
                    priorityQueue.poll();
                    priorityQueue.offer(new int[]{num, count});
                }
            }else{
                priorityQueue.offer(new int[]{num, count});
            }
        }
        int[] res = new int[k];
        for(int i = 0; i < k; i++){
            res[i] = priorityQueue.poll()[0];
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值