Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Last active June 22, 2019 09:56
Show Gist options
  • Save yangpeng-chn/8238828d0e1b1a4ec131090f32838719 to your computer and use it in GitHub Desktop.
Save yangpeng-chn/8238828d0e1b1a4ec131090f32838719 to your computer and use it in GitHub Desktop.
Top K elements
//max heap
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> um;
for(auto num : nums)
um[num]++;
vector<int> res;
priority_queue<pair<int,int>>pq; //max heap
for(auto it = um.begin(); it != um.end(); it++){
pq.push(make_pair(it->second, it->first)); //(occurence, element), sort by occurence
if(pq.size() > um.size() - k){ //um.size() is the number of unique element, 1 <= k <= um.size().
res.push_back(pq.top().second); //element
pq.pop();
}
}
return res;
}
//min heap
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> um;
for(auto num : nums)
um[num]++;
vector<int> res;
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>>pq; //min heap
for(auto it = um.begin(); it != um.end(); it++){
pq.push(make_pair(it->second, it->first)); //(occurence, element), sort by occurence
if(pq.size() > k)
pq.pop();
}
while(!pq.empty()){
res.push_back(pq.top().second);
pq.pop();
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment