aboutsummaryrefslogtreecommitdiff
path: root/top_k_freq_words.cpp
blob: eaf31d5f6c50833ac099f07349679fbecf530f9a (plain)
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
#include "leetcode.h"

struct Compare {
  bool operator()(pair<int, string> a, pair<int, string> b) {
    if (a.first == b.first)
      return a.second > b.second;
    else
      return a.first < b.first;
  }
};

class Solution {
public:
  vector<string> topKFrequent(vector<string> &words, int k) {
    unordered_map<string, int> um;
    for (int i = 0; i < words.size(); i++)
      um[words[i]]++;
    priority_queue<pair<int, string>, vector<pair<int, string>>, Compare>
        pqpvpc;
    for (auto i : um)
      pqpvpc.push({i.second, i.first});
    vector<string> ans;
    while (k--) {
      ans.push_back(pqpvpc.top().second);
      pqpvpc.pop();
    }
    return ans;
  }
};