【重点】【堆】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;
    }
}
相关推荐
TAMOXL18 小时前
ctf.show pwn入门 堆利用-前置基础 pwn142
pwn·
TAMOXL21 小时前
NSSCTF [NISACTF 2022]ezheap
pwn·
whoarethenext20 天前
数据结构堆的c/c++的实现
c语言·数据结构·c++·
小徐Chao努力24 天前
【堆】最大堆、最小堆以及GO语言的实现
数据结构·算法·golang·
sml259(劳改版)2 个月前
数据结构--堆
数据结构·算法·
代码AC不AC2 个月前
【数据结构】堆
c语言·数据结构·学习··深度剖析
ゞ 正在缓冲99%…2 个月前
leetcode295.数据流的中位数
java·数据结构·算法·leetcode·
hnjzsyjyj2 个月前
AcWing 839:模拟堆 ← multiset + unordered_map
橘颂TA2 个月前
【C++】树和二叉树的实现(上)
数据结构·算法·二叉树·
azaz_plus2 个月前
C++ priority_queue 堆
开发语言·c++·stl··priority_queue