小根堆,先用哈希表计数,然后放进堆中,这里不能使用大根堆,不能同时保证频率相同的字典序排序,时间复杂度:
class Solution {public:vector<string> topKFrequent(vector<string>& words, int k) {unordered_map<string,int> hash;typedef pair<int,string> PIS;for(auto& word:words){hash[word]++;}priority_queue<PIS> heap;for(auto& item:hash){// 存次数的相反数,小根堆,堆顶是大数,也就是次数最小的PIS t(-item.second,item.first);heap.push(t);if(heap.size()>k) heap.pop();}vector<string> res(k);for(int i=k-1;i>=0;i--){res[i] = heap.top().second;heap.pop();}return res;}};
