-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap5.cpp
36 lines (33 loc) · 873 Bytes
/
heap5.cpp
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
// q5- Top K frequent numbers
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;
// first answer without watching idea video or gpt
vector<int> q5(vector<int> arr, int k)
{
int n = arr.size();
unordered_map<int, int> map;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> queue;
for (int i = 0; i < n; i++)
{
map[arr[i]]++;
}
for (auto c : map)
{ // insertion mistake, queue check first value of pair which is key, so interchange it with frequency
queue.push({c.first, c.second});
if (queue.size() > k)
{
queue.pop();
}
}
vector<int> result;
while (!queue.empty())
{
result.push_back((queue.top()).first);
queue.pop();
}
return result;
}
// time complexity O(n logK)