1. 程式人生 > >***Leetcode 692. Top K Frequent Words

***Leetcode 692. Top K Frequent Words

用於練習優先隊列了。。實際排序也行


struct cmp {
  bool operator() (const auto& a, const auto&b) {
      if (a.second != b.second) return a.second < b.second;
      return a.first > b.first;
  }  
};

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        priority_queue< pair<string, int>, vector< pair<string, int> >, cmp > q;
        unordered_map< string, int > mp;
        for (int i = 0; i < words.size(); i++) {
            mp[ words[i] ] ++;
        }
        for (auto p: mp) {
            q.push( make_pair(p.first, p.second) );
        }
        vector<string> ret;
        while (!q.empty()) {
            ret.push_back( q.top().first );
            q.pop();
            if (ret.size() >= k) break;
        }
        return ret;
    }
};