forked from fengvyi/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
347. Top K Frequent Elements.cpp
64 lines (61 loc) · 1.79 KB
/
347. 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Solution 1. MaxHeap, O(nlogn).
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int>m;
for(auto x: nums) m[x]++;
priority_queue<pair<int, int>>pq;
for(auto p: m) pq.push({p.second, p.first});
vector<int>res;
while(k--) res.push_back(pq.top().second), pq.pop();
return res;
}
};
// O(nlog(n - k)).
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int>m;
for(auto x: nums) m[x]++;
priority_queue<pair<int, int>>pq;
vector<int>res;
for(auto p: m){
pq.push({p.second, p.first});
if(pq.size() > m.size() - k){
res.push_back(pq.top().second);
pq.pop();
}
}
return res;
}
};
// Solution 2. MinHeap, O(nlogk).
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int>m;
for(auto x: nums) m[x]++;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>pq;
for(auto p: m){
pq.push({p.second, p.first});
if(pq.size() > k) pq.pop();
}
vector<int>res;
while(k--) res.push_back(pq.top().second), pq.pop();
return res;
}
};
// Solution 3. Bucket Sort, O(n).
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int>m;
for(auto x: nums) m[x]++;
vector<int>res;
vector<vector<int>>bucket(nums.size() + 1);
for(auto p: m) bucket[p.second].push_back(p.first);
for(int i = bucket.size() - 1; res.size() < k; i--)
for(auto j: bucket[i]) res.push_back(j);
return res;
}
};