LeetCode 692. 前K個高頻單詞 (善用STL)

前K個高頻單詞

class Solution {
public:
    unordered_map<string,int> m;
    typedef pair<int,string> P;
    priority_queue<P,vector<P>,greater<P> > pq;
    vector<string> ans;
    vector<string> topKFrequent(vector<string>& words, int k) {
        for(string& s:words) m[s]++;
        for(auto it:m) pq.push(make_pair(-it.second,it.first));
        for(int i=0;i<k;i++){
            ans.push_back(pq.top().second);
            pq.pop();
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章