Cover image for LeetCode Hot 100 P347 Top K Frequent Elements

LeetCode Hot 100 P347 Top K Frequent Elements

Words 356
Views
Visitors

Timeline

Timeline

2026-03-19

init

heap

Problem:

max heap

12345678910111213141516171819202122232425262728293031323334
#include <vector>#include <unordered_map>#include <queue>#include <utility>using std::vector;using std::unordered_map;using std::priority_queue;using std::pair;class Solution {    public:        vector<int> topKFrequent(vector<int> &nums, int k)        {                vector<int> res;                unordered_map<int, int> umap;                priority_queue<pair<int, int>, vector<pair<int, int> >, std::less<pair<int, int> > >                        max_heap;                for (int val : nums)                        umap[val]++;                for (auto [val, times] : umap)                        max_heap.push({ times, val });                while (k > 0) {                        res.push_back(max_heap.top().second);                        max_heap.pop();                        k--;                }                return res;        }};

Actually, the optimal solution is to use quicksort:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
#include <vector>#include <unordered_map>#include <utility>using std::pair;using std::vector;using std::unordered_map;class Solution {    private:        void quick_sort(vector<pair<int, int> > &arr, int k, int start, int end)        {                if (start >= end)                        return;                int pivot = arr[(start + end) / 2].first;                int left = start - 1;                int right = end + 1;                while (left < right) {                        do {                                left++;                        } while (arr[left].first > pivot);                        do {                                right--;                        } while (arr[right].first < pivot);                        if (left < right)                                std::swap(arr[left], arr[right]);                }                // start ..=right, right+1..=end                if (k <= right)                        quick_sort(arr, k, start, right);                else                        quick_sort(arr, k, right + 1, end);        }    public:        vector<int> topKFrequent(vector<int> &nums, int k)        {                int i;                vector<pair<int, int> > arr;                unordered_map<int, int> umap;                vector<int> res;                for (int val : nums)                        umap[val]++;                for (auto [val, times] : umap)                        arr.push_back({ times, val });                quick_sort(arr, k, 0, arr.size() - 1);                for (i = 0; i < k; i++)                        res.push_back(arr[i].second);                return res;        }};
Loading comments…