Created
July 30, 2016 00:27
-
-
Save jianminchen/c3d49c11c090b91c94ae7b05bdc11786 to your computer and use it in GitHub Desktop.
LC 347 K most Frequent - C++ bucket sort - source code blog: http://xpharry.org/2016/06/23/347-top-k-frequent-elements-my-submissions-questioneditorial-solution/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<int> topKFrequent(vector<int>& nums, int k) { | |
unordered_map<int,int> m; | |
for(int num : nums) { | |
m[num]++; | |
} | |
vector<vector<int>> buckets(nums.size()+1); | |
for(auto p : m) { | |
buckets[p.second].push_back(p.first); // second:frequency, first:num | |
} | |
vector<int> ans; | |
for(int i = buckets.size()-1; i >= 0 && ans.size() < k; --i) { | |
for(int num : buckets[i]) { | |
ans.push_back(num); | |
if(ans.size() == k) | |
break; // this can only jump out the inner loop | |
} | |
} | |
return ans; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment