Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 30, 2016 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/88f3e2d441c62ecb7d9d706d1b9bda37 to your computer and use it in GitHub Desktop.
Save jianminchen/88f3e2d441c62ecb7d9d706d1b9bda37 to your computer and use it in GitHub Desktop.
LC 347 K most frequent - C++ - bucket sort - code blog: http://storypku.com/2016/05/leetcode-question-347-top-k-frequent-elements/
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
std::unordered_map<int, int> mapping;
for(auto v: nums) {
mapping[v] ++;
}
std::vector<vector<int> > buckets(nums.size() + 1);
for(auto ipair: mapping) {
buckets[ipair.second].push_back(ipair.first);
}
std::vector<int> result;
for(int i = buckets.size() - 1; i >= 0 && result.size() < k; --i) {
for(auto elem: buckets[i]) {
result.push_back(elem);
if (result.size() == k)
break;
}
}
return result;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment