力扣 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;
    }
}
相关推荐
Yzzz-F3 分钟前
Problem - 2167F - Codeforces
算法
MORE_774 分钟前
leecode100-跳跃游戏-贪心算法
算法·游戏·贪心算法
机器学习之心7 分钟前
基于GSWOA-SVM三种策略改进鲸鱼算法优化支持向量机的数据多变量时间序列预测,Matlab代码
算法·支持向量机·matlab·优化支持向量机·gswoa-svm·三种策略改进鲸鱼算法
旖-旎12 分钟前
前缀和(和为K的子数组)(5)
c++·算法·leetcode·前缀和·哈希算法·散列表
进击的荆棘16 分钟前
优选算法——链表
数据结构·算法·链表·stl
凌波粒19 分钟前
LeetCode--203.移除链表元素(链表)
java·算法·leetcode·链表
榴莲omega20 分钟前
第8天:前端面试经典五问
前端·面试·职场和发展·js八股
不染尘.21 分钟前
背包问题BP
开发语言·c++·算法
进击的小头23 分钟前
第17篇:卡尔曼滤波器之概率论初步
python·算法·概率论
2401_8747325323 分钟前
基于C++的爬虫框架
开发语言·c++·算法