【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;
    }
};
相关推荐
不穿格子的程序员20 小时前
从零开始刷算法-单调栈-每日温度
算法·单调栈
麦烤楽鸡翅20 小时前
挡住洪水 (牛客)
java·数据结构·c++·python·算法·bfs·牛客
MicroTech202520 小时前
微算法科技(NASDAQ MLGO)采用动态层次管理和位置聚类技术,修改pBFT算法以提高私有区块链网络运行效率
科技·算法·聚类
~~李木子~~20 小时前
五子棋项目Alpha-Beta剪枝与MCTS+神经网络实现人机对弈算法对比报告
神经网络·算法·剪枝
bigdata-rookie20 小时前
JVM 垃圾收集器介绍
java·jvm·算法
ʚ希希ɞ ྀ20 小时前
leeCode hot 100 !!!持续更新中
数据结构·算法·leetcode
lemontree194520 小时前
CRC8算法通用版本
算法
热爱生活的猴子20 小时前
算法322. 零钱兑换
算法
剪一朵云爱着20 小时前
力扣1539. 第 k 个缺失的正整数
算法·leetcode
摸鱼仙人~20 小时前
针对编程面试和算法题的基础书籍
算法·面试·职场和发展