top-k-frequent-elements 1.0.0
Top K Frequent Elements
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
6{
7public:
8 vector<int> topKFrequent(vector<int>& nums, int k)
9 {
10 unordered_map<int, int> occurrences; // (num, occurrences)
11 for (int el: nums)
12 occurrences[el]++;
13
14 auto comparator = [](pair<int, int>& A, pair<int, int>& B)
15 {
16 return A.second > B.second; // min-heap by frequency
17 };
18 priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comparator)> min_heap(comparator);
19
20 for (const pair<const int, int>& occ: occurrences)
21 {
22 min_heap.push(occ);
23 if ((int)min_heap.size() > k)
24 min_heap.pop(); // remove the least frequent element if size exceeds k
25 }
26
27 vector<int> answer;
28 while (!min_heap.empty())
29 {
30 answer.push_back(min_heap.top().first);
31 min_heap.pop();
32 }
33 return answer;
34 }
35};
36
37
38int main()
39{
40
41 return 0;
42}
vector< int > topKFrequent(vector< int > &nums, int k)
Definition main.cpp:8
int main()
Definition main.cpp:38