小根堆,先用哈希表计数,然后放进堆中,这里不能使用大根堆,不能同时保证频率相同的字典序排序,时间复杂度:Leetcode 692. 前K个高频词 - 图1

    1. class Solution {
    2. public:
    3. vector<string> topKFrequent(vector<string>& words, int k) {
    4. unordered_map<string,int> hash;
    5. typedef pair<int,string> PIS;
    6. for(auto& word:words){
    7. hash[word]++;
    8. }
    9. priority_queue<PIS> heap;
    10. for(auto& item:hash){
    11. // 存次数的相反数,小根堆,堆顶是大数,也就是次数最小的
    12. PIS t(-item.second,item.first);
    13. heap.push(t);
    14. if(heap.size()>k) heap.pop();
    15. }
    16. vector<string> res(k);
    17. for(int i=k-1;i>=0;i--){
    18. res[i] = heap.top().second;
    19. heap.pop();
    20. }
    21. return res;
    22. }
    23. };