自学内容网 自学内容网

【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;
    }
};

原文地址:https://blog.csdn.net/weixin_62264287/article/details/137875117

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!