Created
July 29, 2016 23:26
-
-
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/
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
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