File tree Expand file tree Collapse file tree 1 file changed +20
-12
lines changed
Expand file tree Collapse file tree 1 file changed +20
-12
lines changed Original file line number Diff line number Diff line change 1+ // TC: O(N), SC: O(N)
12class Solution {
23public:
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};
You can’t perform that action at this time.
0 commit comments