Leetcode 692. Top K Frequent Words 前K个高频单词(最小堆)

博客介绍了如何解决LeetCode的第692题,即找出给定单词列表中出现频率最高的前K个单词。内容包括题目描述、示例、解答和代码实现。解答提出通过先计算单词频率,再利用最小堆来存储并排序前K个高频单词的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode 692. Top K Frequent Words 前K个高频单词:最小堆

692. Top K Frequent Words 前K个高频单词

题目描述

Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Input words contain only lowercase letters.
Follow up:
Try to solve it in O(n log k) time and O(n) extra space.

示例:

Example 1:

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
    Note that "i" comes before "love" due to a lower alphabetical order.

Example 2:

Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
    with the number of occurrence being 4, 3, 2 and 1 respectively.

解答

这道题先扫描一遍数组,记录一下每个单词出现的频率。

然后建立一个最小堆,里面只能存放k个单词,最后将这k个单词安从大到小排列就是前K个高频单词。

代码

class Solution {
public:
 struct comp {
  bool operator()(const pair<string, int> &lhs, const pair<string, int> & rhs) const {
   if (lhs.second == rhs.second) {
    return lhs.first < rhs.first;
   }
   return lhs.second > rhs.second;
  }
 };
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map <string, int> ump;
        for (auto & w : words) {
         ump[w] += 1;
        }

        priority_queue<pair<string, int>, vector<pair<string, int>>, comp> pq;
        for (auto & u : ump) {
         pq.emplace(u.first, u.second);
         if (pq.size() > k) pq.pop();
        }
        vector<string> ans;
        while(!pq.empty()) {
         ans.insert(ans.begin(), pq.top().first);
         pq.pop();
        }
        return ans;
    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值