力扣 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;
    }
}
相关推荐
凌冰_1 分钟前
数据结构 - 矩阵(九)
算法·矩阵
Regulus-Moon7 分钟前
凸优化:局部即全局的定价表——条件数 κ 上的速率谱系
算法·机器学习·数学建模
FPGA小迷弟14 分钟前
PID 算法全解:从历史渊源到 FPGA 硬件实现
算法·fpga开发·硬件架构·fpga·sm4
洞见新研社15 分钟前
半年从蓝海杀入红海,机器人数据生意变天了
人工智能·算法·机器人
纪念 22939 分钟前
C++ 算法模板与错题 (高精度)
开发语言·c++·算法
Interview Aid1121 小时前
Virtu Financial 完整面试指南:OA、Technical Interview 与真实面经
面试·职场和发展
Navigator_Z2 小时前
LeetCode //C - 1331. Rank Transform of an Array
c语言·算法·leetcode
Tisfy2 小时前
LeetCode 1202.交换字符串中的元素:分组排序(连通图)
算法·leetcode·字符串·bfs·题解·排序·连通图
csdn_aspnet9 小时前
C++ 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
c++·算法