力扣 LeetCode 347. 前K个高频元素(Day5:栈与队列)

解题思路:

小根堆统计前K个高频元素

注意:

PriorityQueue中需要自定义排序规则

java 复制代码
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        PriorityQueue<int[]> pq = new PriorityQueue<>((x,y)->x[1]-y[1]);
        Map<Integer,Integer> map=new HashMap<>();
        for(int num:nums){
            map.put(num,map.getOrDefault(num,0)+1);
        }

        for(Map.Entry<Integer,Integer> entry:map.entrySet()){
            if(pq.size()<k) pq.add(new int[]{entry.getKey(),entry.getValue()});
            else{
                if(entry.getValue()>pq.peek()[1]){
                    pq.poll();
                    pq.add(new int[]{entry.getKey(),entry.getValue()});

                }
            }
        }
        
        int[] res=new int[k];
        for(int i=0;i<k;i++){
            res[i]=pq.poll()[0];
        }
        return res;
    }
}
相关推荐
西柚研究生1234564 小时前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测
hetao17338374 小时前
2026-09-17 hetao1733837 的刷题记录
c++·算法
午彦琳5 小时前
2026.9.17
数据结构·算法·leetcode
木井巳6 小时前
【记忆化搜索】不同路径
java·算法·leetcode·深度优先·剪枝·推荐算法
怕浪猫7 小时前
从 Windows 换到 Mac 三个月,我真香了
算法·面试·架构
aichitang20247 小时前
前端小skill
前端·人工智能·算法·ai·前端框架
All for pursuit.8 小时前
【链表-9】146.LRU缓存
数据结构·c++·算法·leetcode
木子算法8 小时前
测出来的值会抖:约束和目标带噪声时,「可行」和「更好」该怎么判
人工智能·算法·目标跟踪
圣保罗的大教堂9 小时前
leetcode 1477. 找两个和为目标值且不重叠的子数组 中等
leetcode
hanlin0310 小时前
刷题笔记:力扣第144题-二叉树的前序遍历
笔记·算法·leetcode