Created
July 30, 2016 01:04
-
-
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/
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
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