1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: vector<string> topKFrequent(vector<string>& words, int k) { map<string, int> m; for (const auto& word : words) ++m[word]; auto cmp = [&](const auto& a, const auto& b) { return a.first > b.first || (a.first == b.first && a.second < b.second); }; priority_queue<pair<int, string>, vector<pair<int, string>>, decltype(cmp)> q(cmp); for (const auto& [word, freq] : m) { q.emplace(freq, word); if (q.size() > k) q.pop(); } vector<string> ans(k); for (int i = k - 1; i >= 0; --i) { ans[i] = q.top().second; q.pop(); } return ans; } };
|