【LeetCode热题100】【堆】前 K 个高频元素

题目链接:347. 前 K 个高频元素 - 力扣(LeetCode)

要找出前K个出现频率最多的元素,可以先用哈希表存储每个元素出现的次数,然后建立一个容量为K的小顶堆,遍历哈希表找到更高频的元素入堆进行堆调整,最后堆里的元素就是前K个出现次数最多的元素

手写一个堆,就在答案容器基础上建堆,注意比较需要用哈希表比较

复制代码
class Solution {
public:
    vector<int> ans;
    int heapSize;
    unordered_map<int, int> hash;

    void adjustHeap(int root) {
        int left = 2 * root + 1;
        int right = left + 1;
        int next = root;
        if (left < heapSize && hash[ans[left]] < hash[ans[next]])
            next = left;
        if (right < heapSize && hash[ans[right]] < hash[ans[next]])
            next = right;
        if (next != root) {
            swap(ans[next], ans[root]);
            adjustHeap(next);
        }
    }

    void buildHeap() {
        for (int i = heapSize / 2 - 1; i >= 0; --i)
            adjustHeap(i);
    }

    vector<int> topKFrequent(vector<int> &nums, int k) {
        this->heapSize = k;
        for (auto &num: nums)
            hash[num]++;
        auto &&start = hash.begin();
        while (k--) {
            ans.push_back(start->first);
            ++start;
        }
        buildHeap();
        while (start != hash.end()) {
            if (start->second > hash[ans[0]]) {
                ans[0] = start->first;
                adjustHeap(0);
            }
            ++start;
        }
        return ans;
    }
};
相关推荐
2601_967760786 小时前
2026年PDF压缩与页码添加工具技术实测:性能、算法与本地化适配深度对比
算法·pdf
不会就选b6 小时前
算法日常・每日刷题--<贪心>7
数据结构·算法·leetcode
moonrailgun7 小时前
用 Node.js 复刻 Codex Astra 的终端星光
前端·javascript·算法
罗西的思考7 小时前
[Agent Memory / 强化学习] MemPO源码学习笔记 ---(1)--- 总体
人工智能·算法·机器学习
lvwangshu8 小时前
图论:LCA、树的直径、树的重心、二分图与 Tarjan 缩点
算法·图论
302wanger9 小时前
干与湿:AI 拿走脑力之后,人剩下什么
算法
计算机编程-吉哥10 小时前
脑肿瘤MRI智能识别系统:基于深度学习的像素级脑肿瘤语义分割平台【计算机毕业设计选题推荐】
人工智能·python·深度学习·算法·毕业设计·课程设计·大数据毕业设计选题推荐
用户2049375549510 小时前
端侧语音部署踩坑:模型能跑不等于终端真的能用
后端·算法
shehuiyuelaiyuehao10 小时前
算法39,位运算,消失的两个数字
java·数据结构·算法
ZiLing10 小时前
2026 ROS 2 Lyrical 踩坑实录(一):编译与依赖——rosdep、现代 CMake 与 CMake 4.x
算法