【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;
    }
};
相关推荐
Han.miracle31 分钟前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
mit6.8242 小时前
前后缀分解
算法
你好,我叫C小白3 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林5 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway6 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No76 小时前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区7 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫7 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
liu****7 小时前
8.list的模拟实现
linux·数据结构·c++·算法·list
地平线开发者7 小时前
征程 6 | 征程 6 工具链如何支持 Matmul/Conv 双 int16 输入量化?
算法·自动驾驶