-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path347.cpp
More file actions
26 lines (25 loc) · 698 Bytes
/
347.cpp
File metadata and controls
26 lines (25 loc) · 698 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
class Solution {
public:
class compare {
public:
bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {
return lhs.second > rhs.second;
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> mp;
priority_queue<pair<int, int>, vector<pair<int, int>>, compare> pq;
for (auto& num : nums) mp[num]++;
for (auto p : mp) {
pq.push(p);
if (pq.size() > k) pq.pop();
}
vector<int> res;
while (!pq.empty()) {
auto p = pq.top();
pq.pop();
res.push_back(p.first);
}
return res;
}
};