【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;
    }
};
相关推荐
大千AI助手1 小时前
DTW模版匹配:弹性对齐的时间序列相似度度量算法
人工智能·算法·机器学习·数据挖掘·模版匹配·dtw模版匹配
YuTaoShao3 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
生态遥感监测笔记3 小时前
GEE利用已有土地利用数据选取样本点并进行分类
人工智能·算法·机器学习·分类·数据挖掘
Tony沈哲4 小时前
macOS 上为 Compose Desktop 构建跨架构图像处理 dylib:OpenCV + libraw + libheif 实践指南
opencv·算法
刘海东刘海东4 小时前
结构型智能科技的关键可行性——信息型智能向结构型智能的转变(修改提纲)
人工智能·算法·机器学习
pumpkin845145 小时前
Rust 调用 C 函数的 FFI
c语言·算法·rust
挺菜的5 小时前
【算法刷题记录(简单题)003】统计大写字母个数(java代码实现)
java·数据结构·算法
mit6.8245 小时前
7.6 优先队列| dijkstra | hash | rust
算法
2401_858286115 小时前
125.【C语言】数据结构之归并排序递归解法
c语言·开发语言·数据结构·算法·排序算法·归并排序