Untitled
unknown
plain_text
2 years ago
569 B
8
Indexable
class Solution { //priority queue
public:
vector<int> topKFrequent(vector<int>& arr, int k) {
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
unordered_map<int,int> fr;
for(auto x:arr) fr[x]++;
for(auto m:fr){
pq.push({m.second,m.first}); //frequency , elemnt
if(pq.size()>k) pq.pop();
}
vector<int> res;
while(!pq.empty()){
res.push_back(pq.top().second);
pq.pop();
}
return res;
}
};Editor is loading...