1. 程式人生 > 其它 >【力扣 076】692. 前K個高頻單詞

【力扣 076】692. 前K個高頻單詞

692. 前K個高頻單詞

給定一個單詞列表 words 和一個整數 k ,返回前 k 個出現次數最多的單詞。

返回的答案應該按單詞出現頻率由高到低排序。如果不同的單詞有相同出現頻率, 按字典順序 排序。

示例 1:

輸入: words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2
輸出: ["i", "love"]
解析: "i" 和 "love" 為出現次數最多的兩個單詞,均為2次。
    注意,按字母順序 "i" 在 "love" 之前。
示例 2:

輸入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
輸出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出現次數最多的四個單詞,
    出現次數依次為 4, 3, 2 和 1 次。
 

注意:

1 <= words.length <= 500
1 <= words[i] <= 10
words[i] 由小寫英文字母組成。
k 的取值範圍是 [1, 不同 words[i] 的數量]

來源:力扣(LeetCode)
連結:https://leetcode.cn/problems/top-k-frequent-words
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

方法一、優先佇列

程式碼實現:

class Solution {
public:
  vector<string> topKFrequent(vector<string> &words, int k)
  {
    unordered_map<string, int> cnt;
    for (auto &word : words)
    {
      cnt[word]++;
    }
    auto cmp = [](const pair<string, int> &a, const pair<string, int> &b)
    {
      return a.second == b.second ? a.first < b.first : a.second > b.second;
    };
    priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(cmp)> que(cmp);
    for (auto &it : cnt)
    {
      que.emplace(it);
      if (que.size() > k)
      {
        que.pop();
      }
    }
    vector<string> ret(k);
    for (int i = k - 1; i >= 0; i--)
    {
      ret[i] = que.top().first;
      que.pop();
    }
    return ret;
  }
};