nikunjsoni

692

May 25th, 2021
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.57 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<string> topKFrequent(vector<string>& words, int k) {
  4.         unordered_map<string, int> freq;
  5.         for(auto w : words)
  6.             freq[w]++;
  7.  
  8.         priority_queue<pair<int, string>> pq;
  9.        
  10.         for(auto w: freq){
  11.             pq.push({-w.second, w.first});
  12.             if(pq.size()>k) pq.pop();
  13.         }
  14.        
  15.         vector<string> res;
  16.         while(!pq.empty()){
  17.             res.push_back(pq.top().second);
  18.             pq.pop();
  19.         }
  20.         reverse(res.begin(), res.end());
  21.         return res;
  22.     }
  23. };
Advertisement
Add Comment
Please, Sign In to add comment