Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 29, 2016 23:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jianminchen/cd9f536708f6ec42ae229d853c881361 to your computer and use it in GitHub Desktop.
Save jianminchen/cd9f536708f6ec42ae229d853c881361 to your computer and use it in GitHub Desktop.
Leetcode 347 - top k frequent elements in the array - C++ solution to study - code source: https://www.hrwhisper.me/leetcode-top-k-frequent-elements/
typedef pair<int, int> P;
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> cnt;
for (int x : nums) cnt[x] ++;
priority_queue<P, vector<P>, greater<P> > q;
for (auto &x : cnt) {
if (q.size() < k)
q.push(make_pair(x.second, x.first));
else {
if (q.top().first < x.second) {
q.pop();
q.push(make_pair(x.second, x.first));
}
}
}
vector<int> ans;
while (!q.empty()) {
ans.push_back(q.top().second);
q.pop();
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment