-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
42 lines (34 loc) · 988 Bytes
/
main.cpp
File metadata and controls
42 lines (34 loc) · 988 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> topKFrequent(vector<int>& nums, int k)
{
unordered_map<int, int> occurrences; // (num, occurrences)
for (int el: nums)
occurrences[el]++;
auto comparator = [](pair<int, int>& A, pair<int, int>& B)
{
return A.second > B.second; // min-heap by frequency
};
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comparator)> min_heap(comparator);
for (const pair<const int, int>& occ: occurrences)
{
min_heap.push(occ);
if ((int)min_heap.size() > k)
min_heap.pop(); // remove the least frequent element if size exceeds k
}
vector<int> answer;
while (!min_heap.empty())
{
answer.push_back(min_heap.top().first);
min_heap.pop();
}
return answer;
}
};
int main()
{
return 0;
}