力扣 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;
    }
}
相关推荐
暖阳华笺9 分钟前
【高频考点】回溯(暴力搜索)
数据结构·c++·算法·回溯法
hunterkkk(c++)9 分钟前
学习dijkstra算法(c++)
c++·学习·算法
我命由我1234514 分钟前
Excel - Excel 覆盖模式与编辑模式
运维·学习·职场和发展·excel·求职招聘·职场发展·运维开发
lightqjx18 分钟前
【算法】数据结构_单调队列
数据结构·算法·单调队列
小四季豆27 分钟前
《数据结构与算法》-顺序表:算法落地的第一个线性结构
c语言·数据结构·算法
8Qi834 分钟前
LeetCode 96:不同的二叉搜索树(Unique Binary Search Trees)—— 题解 ✅
算法·leetcode·职场和发展·动态规划
1892280486135 分钟前
NV041固态MT29F16T08GSLCEM9-QBES:C
人工智能·算法·microsoft·缓存·性能优化
罗超驿1 小时前
15.LeetCode 30. 串联所有单词的子串(Java):滑动窗口+哈希表详解
算法·leetcode
Marianne Qiqi1 小时前
非hot100的力扣算法题
数据结构·算法·leetcode
CC数学建模1 小时前
2026第八届中青杯全国大学生数学建模竞赛C题:情绪维度耦合约束的脑电信号情绪识别 (1)完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模