692. 前K个高频单词
1 class Solution 2 { 3 struct cmp 4 { 5 bool operator()(pair<string,int> const &left,pair<string,int> const &right) 6 { 7 if(left.second == right.second) return left.first > right.first; 8 return left.second < right.second; 9 } 10 }; 11 12 public: 13 vector<string> topKFrequent(vector<string>& words, int k) 14 { 15 priority_queue<pair<string,int>,vector<pair<string,int>>,cmp> pq; 16 unordered_map<string,int> hash; 17 for(auto a : words) hash[a] ++; 18 for(auto a : hash) pq.push({a.first,a.second}); 19 20 vector<string> ans; 21 while(k --) 22 { 23 ans.push_back(pq.top().first); 24 pq.pop(); 25 } 26 return ans; 27 } 28 };
Mamba never out

浙公网安备 33010602011771号