力扣 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;
    }
}
相关推荐
lihihi16 分钟前
P1209 [USACO1.3] 修理牛棚 Barn Repair
算法
weixin_3875342235 分钟前
Ownership - Rust Hardcore Head to Toe
开发语言·后端·算法·rust
xsyaaaan35 分钟前
leetcode-hot100-链表
leetcode·链表
庞轩px41 分钟前
MinorGC的完整流程与复制算法深度解析
java·jvm·算法·性能优化
Queenie_Charlie1 小时前
Manacher算法
c++·算法·manacher
闻缺陷则喜何志丹1 小时前
【树的直径 离散化】 P7807 魔力滋生|普及+
c++·算法·洛谷·离散化·树的直径
AI_Ming1 小时前
Seq2Seq-大模型知识点(程序员转行AI大模型学习)
算法·ai编程
若水不如远方1 小时前
分布式一致性(六):拥抱可用性 —— 最终一致性与 Gossip 协议
分布式·后端·算法
计算机安禾1 小时前
【C语言程序设计】第35篇:文件的打开、关闭与读写操作
c语言·开发语言·c++·vscode·算法·visual studio code·visual studio
Wect1 小时前
React Hooks 核心原理
前端·算法·typescript