【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;
    }
};
相关推荐
我家大宝最可爱9 分钟前
动态规划:入门思考篇
算法·动态规划·代理模式
肉夹馍不加青椒20 分钟前
第三十三天(信号量)
java·c语言·算法
古译汉书1 小时前
嵌入式-SPI番外之按钮驱动程序的编写-Day15
c语言·stm32·单片机·嵌入式硬件·mcu·算法
快去睡觉~1 小时前
力扣48:旋转矩阵
算法·leetcode·矩阵
卡洛斯(编程版3 小时前
(1) 哈希表全思路-20天刷完Leetcode Hot 100计划
python·算法·leetcode
NAGNIP4 小时前
DeepSeekMoE 架构解析
算法
不喜欢学数学er4 小时前
算法第五十二天:图论part03(第十一章)
算法·深度优先·图论
养成系小王4 小时前
四大常用排序算法
数据结构·算法·排序算法
NAGNIP4 小时前
一文搞懂DeepSeek LLM
算法
已读不回1434 小时前
设计模式-策略模式
前端·算法·设计模式