471. Top K Frequent Words

ode(Language:C++)
class Solution {
public:
    /**
     * @param words: an array of string
     * @param k: An integer
     * @return: an array of string
     */
    struct node{
       string word; 
       int freq; 
       node(string word, int freq){
           this->word = word;
           this->freq = freq; 
       }
    };
    struct cmp{
        bool operator()(const node &a, const node &b){
            return a.freq > b.freq || (a.freq == b.freq && a.word < b.word); 
        }
    }; 
    vector<string> topKFrequentWords(vector<string> &words, int k) {
        // write your code here
        //统计次数; 以次数作为primary排序, pq 
        unordered_map<string, int> mp;
        vector<string> res; 
        const int size = words.size();
        if(size == 0){
            return res; 
        }
        for(auto i : words){
            mp[i]++; 
        }
        priority_queue<node, vector<node>, cmp> pq; 
        for(auto i : mp){
            pq.push(node(i.first, i.second));
            if(pq.size() > k){
                pq.pop(); 
            }
        }
        while(!pq.empty()){
            res.push_back(pq.top().word);
            pq.pop(); 
        }
        reverse(res.begin(), res.end());
        return res; 
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

Comments

Popular posts from this blog

算法的比较

生命