Skip to content

Commit 844a96d

Browse files
committed
fix top-k-freq-elements
1 parent 4aad6ff commit 844a96d

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed
Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,31 @@
1+
// TC: O(N), SC: O(N)
12
class Solution {
23
public:
34
vector<int> topKFrequent(vector<int>& nums, int k) {
4-
unordered_map<int, int> m;
5-
map<int, vector<int>> freq;
6-
for(auto i: nums) m[i] += 1;
7-
for(auto item: m) {
8-
auto [k, v] = item;
9-
freq[v].push_back(k);
5+
unordered_map<int, int> freq;
6+
freq.reserve(nums.size() * 2);
7+
for (int x : nums) {
8+
++freq[x];
9+
}
10+
11+
int n = nums.size();
12+
vector<vector<int>> bucket(n + 1);
13+
for (auto& p : freq) {
14+
int num = p.first;
15+
int cnt = p.second;
16+
bucket[cnt].push_back(num);
1017
}
1118

1219
vector<int> ans;
1320
ans.reserve(k);
14-
auto it = freq.rbegin();
15-
while(k > 0) {
16-
auto kth = it->second;
17-
ans.insert(ans.end(), kth.begin(), kth.end());
18-
k-=kth.size();
19-
it++;
21+
22+
for (int count = n; count >= 1 && ans.size() < k; --count) {
23+
for (int num : bucket[count]) {
24+
ans.push_back(num);
25+
if (ans.size() == k) break;
26+
}
2027
}
28+
2129
return ans;
2230
}
2331
};

0 commit comments

Comments
 (0)