-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathTop_K_Frequent_Elements.cpp
37 lines (36 loc) · 1.06 KB
/
Top_K_Frequent_Elements.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
37
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> result;
if(k == 0 or nums.empty()) return result;
result.resize(k);
int n = (int)nums.size();
unordered_map<int, int> freq;
// O(n)
for(int i = 0; i < n; ++i) {
if(freq.find(nums[i]) == freq.end()) {
freq[nums[i]] = 0;
}
freq[nums[i]]++;
}
// O(nlogk)
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > Q;
for(auto it = freq.begin(); it != freq.end(); ++it) {
if(Q.size() < k) {
Q.push({it->second, it->first});
} else {
if(it->second > Q.top().first) {
Q.pop();
Q.push({it->second, it->first});
}
}
}
// O(klogk)
int i = k - 1;
while(!Q.empty()) {
result[i--] = Q.top().second;
Q.pop();
}
return result;
}
};