LeetCode 692. Top K Frequent Words
和top k element一样的题目。创建大顶堆,pop前k个就是所求。nlogn
也可以创建一个大小为k的小顶堆,这样最后留下的就是最大的k个元素。小顶堆和大顶堆正好相反,在cmp函数写的时候,除了a.second>b.second, if (a.second==b.second) return a.first<b.first; 几个符号都要反转。时间复杂度O(nlogk)
class Solution { public: struct cmp{ bool operator() (const pair<string,int> &a, const pair<string,int> &b) const{ if (a.second==b.second) return a.first<b.first; return a.second>b.second; } }; vector<string> topKFrequent(vector<string>& words, int k) { vector<string> res; unordered_map<string,int> hash; for (string word:words) ++hash[word]; priority_queue<pair<string,int>, vector<pair<string,int>>, cmp> q; for (auto x:hash){ q.push({x.first,x.second}); if (q.size()>k) q.pop(); } while (!q.empty()){ res.push_back(q.top().first); q.pop(); } reverse(res.begin(),res.end()); return res; } };
上述方法把word和count作为一个pair放入pq中。我们当然也可以不用pair,只放word,这样hash作为全局变量会比较好。也可以用lambda function来写比较函数,用 [&] 引用传递hash,写起来更加简洁。
class Solution { public: vector<string> topKFrequent(vector<string>& words, int k) { vector<string> res; unordered_map<string,int> hash; for (string word:words) ++hash[word]; auto cmp=[&](const string &a, const string &b){ if (hash[a]!=hash[b]) return hash[a]>hash[b]; else return a<b; }; priority_queue<string,vector<string>,decltype(cmp)> q(cmp); for (auto [key,val]:hash){ q.push(key); if (q.size()>k) q.pop(); } while (!q.empty()){ res.push_back(q.top()); q.pop(); } reverse(res.begin(),res.end()); return res; } };

浙公网安备 33010602011771号