-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0347-top-k-frequent-elements.cpp
65 lines (55 loc) · 1.75 KB
/
0347-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
/*
Given an integer array nums & an integer k, return the k most frequent elements
Ex. nums = [1,1,1,2,2,3] k = 2 -> [1,2], nums = [1] k = 1 -> [1]
Heap -> optimize w/ freq map & bucket sort (no freq can be > n), get results from end
*/
// Time: O(n log k)
// Space: O(n + k)
// class Solution {
// public:
// vector<int> topKFrequent(vector<int>& nums, int k) {
// unordered_map<int, int> m;
// for (int i = 0; i < nums.size(); i++) {
// m[nums[i]]++;
// }
// priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
// for (auto it = m.begin(); it != m.end(); it++) {
// pq.push({it->second, it->first});
// if (pq.size() > k) {
// pq.pop();
// }
// }
// vector<int> result;
// while (!pq.empty()) {
// result.push_back(pq.top().second);
// pq.pop();
// }
// return result;
// }
// };
// Time: O(n)
// Space: O(n)
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
int n = nums.size();
unordered_map<int, int> m;
for (int i = 0; i < n; i++) {
m[nums[i]]++;
}
vector<vector<int>> buckets(n + 1);
for (auto it = m.begin(); it != m.end(); it++) {
buckets[it->second].push_back(it->first);
}
vector<int> result;
for (int i = n; i >= 0; i--) {
if (result.size() >= k) {
break;
}
if (!buckets[i].empty()) {
result.insert(result.end(), buckets[i].begin(), buckets[i].end());
}
}
return result;
}
};