思路:
堆。
实现:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 class Solution 5 { 6 public: 7 inline bool cmp(pair<int, string> a, pair<int, string> b) 8 { 9 if (a.first > b.first) return true; 10 if (a.first == b.first && a.second < b.second) return true; 11 return false; 12 } 13 struct cmp1 14 { 15 bool operator()(const pair<int, string>& a, const pair<int, string>& b) const 16 { 17 if (a.first > b.first) return true; 18 if (a.first == b.first && a.second < b.second) return true; 19 return false; 20 } 21 }; 22 vector<string> topKFrequent(vector<string>& words, int k) 23 { 24 unordered_map<string, int> mp; 25 for (auto it : words) mp[it]++; 26 priority_queue<pair<int, string>, vector<pair<int, string>>, cmp1> q; 27 int cnt = 0; 28 for (auto it : mp) 29 { 30 pair<int, string> tmp(it.second, it.first); 31 if (cnt < k) 32 { 33 q.push(tmp); 34 } 35 else if (cmp(tmp, q.top())) 36 { 37 q.push(tmp); 38 q.pop(); 39 } 40 cnt++; 41 } 42 vector<string> ret; 43 while (!q.empty()) 44 { 45 ret.push_back(q.top().second); q.pop(); 46 } 47 reverse(ret.begin(), ret.end()); 48 return ret; 49 } 50 }; 51 int main() 52 { 53 vector<string> v = {"i", "love", "leetcode", "i", "love", "coding"}; 54 vector<string> ret = Solution().topKFrequent(v, 2); 55 for (auto it : ret) 56 { 57 cout << it << " "; 58 } 59 cout << endl; 60 return 0; 61 }