forked from Divya063/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
top-k-frequent-elements.cpp
78 lines (74 loc) · 2.04 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
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Time: O(n)
// Space: O(n)
// Bucket Sort Solution
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> counts;
for (const auto& i : nums) {
++counts[i];
}
vector<vector<int>> buckets(nums.size() + 1);
for (const auto& kvp : counts) {
buckets[kvp.second].emplace_back(kvp.first);
}
vector<int> result;
for (int i = buckets.size() - 1; i >= 0; --i) {
for (int j = 0; j < buckets[i].size(); ++j){
result.emplace_back(buckets[i][j]);
if (result.size() == k) {
return result;
}
}
}
return result;
}
};
// Time: O(n) ~ O(n^2), O(n) on average.
// Space: O(n)
// Quick Select Solution
class Solution2 {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> counts;
for (const auto& i : nums) {
++counts[i];
}
vector<pair<int, int>> p;
for (const auto& kvp : counts) {
p.emplace_back(-kvp.second, kvp.first);
}
nth_element(p.begin(), p.begin() + k - 1, p.end());
vector<int> result;
for (int i = 0; i < k; ++i) {
result.emplace_back(p[i].second);
}
return result;
}
};
// Time: O(nlogk)
// Space: O(n)
// Heap solution.
class Solution3 {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> counts;
for (const auto& i : nums) {
++counts[i];
}
priority_queue<pair<int, int>> heap;
for (const auto& kvp : counts) {
heap.emplace(-kvp.second, kvp.first);
if (heap.size() == k + 1) {
heap.pop();
}
}
vector<int> result;
while (!heap.empty()) {
result.emplace_back(heap.top().second);
heap.pop();
}
reverse(result.begin(), result.end());
return result;
}
};