【重点】【堆】347.前K个高频元素

题目

最大的K个元素 => 小根堆(类似上窄下宽的梯形)

最小的K个元素 => 大根堆(类似倒三角形)

法1:小根堆

java 复制代码
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> valToCountMap = new HashMap<>();
        for (int i : nums) {
            valToCountMap.put(i, valToCountMap.getOrDefault(i, 0) + 1);
        }
        PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[1] - b[1]);
        for (Map.Entry<Integer, Integer> entry : valToCountMap.entrySet()) {
            int val = entry.getKey(), count = entry.getValue();
            if (queue.size() == k) {
                if (count > queue.peek()[1]) {
                    queue.poll();
                    queue.offer(new int[]{val, count});
                }
            } else {
                queue.offer(new int[]{val, count});
            }
        }

        int[] res = new int[k];
        for (int i = 0; i < k; ++i) {
            res[i] = queue.poll()[0];
        }

        return res;
    }
}
相关推荐
sml259(劳改版)18 天前
数据结构--堆
数据结构·算法·
代码AC不AC22 天前
【数据结构】堆
c语言·数据结构·学习··深度剖析
ゞ 正在缓冲99%…22 天前
leetcode295.数据流的中位数
java·数据结构·算法·leetcode·
hnjzsyjyj1 个月前
AcWing 839:模拟堆 ← multiset + unordered_map
橘颂TA1 个月前
【C++】树和二叉树的实现(上)
数据结构·算法·二叉树·
azaz_plus1 个月前
C++ priority_queue 堆
开发语言·c++·stl··priority_queue
DARLING Zero two♡2 个月前
【初阶数据结构】森林里的树影 “堆” 光:堆
c语言·数据结构·c++··
Ronin-Lotus2 个月前
程序代码篇---C/C++中的变量存储位置
c语言·c++···静态区·文字常量区·变量存储位置
Lostgreen3 个月前
堆(Heap)的原理与C++实现
数据结构·堆排序·
轩情吖3 个月前
二叉树-堆(补充)
c语言·数据结构·c++·后端·二叉树··排序