[M排序] lc692. 前K个高频单词(自定义排序+堆+top(k))

本文介绍了一种使用STL实现的高效方法来提取文本中出现频率最高的前K个单词。通过自定义排序或优先队列实现,适用于需要进行文本分析的应用场景。

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

1. 题目来源

链接:692. 前K个高频单词

2. 题目解析

STL 应用。自定义排序即可,也可以直接用 priority_queue<pair<string, int>> 堆来处理本题。


时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn)
空间复杂度: O ( n ) O(n) O(n)

代码:

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string, int> hs;
        for (auto &e : words) hs[e] ++ ;

        vector<pair<string, int>> a;
        for (auto &e : hs) a.push_back({e.first, e.second});
        sort(a.begin(), a.end(), [](pair<string, int> a, pair<string, int> b) {
            if (a.second == b.second) return a.first < b.first;
            return a.second > b.second;
        });

        vector<string> res;
        for (int i = 0; i < k; i ++ ) res.push_back(a[i].first);
        return res;
    }
};

堆,摘自评论区代码:

#define PSI pair<string, int>
class Solution {
private:
    struct cmp {
        bool operator ()(PSI& a, PSI& b) {
            return a.second == b.second ? a.first < b.first : a.second > b.second;
        }
    };
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        int n = words.size();
        unordered_map<string, int> hash;
        for (auto& e : words) {
            ++hash[s];
        }
        priority_queue<PSI, vector<PSI>, cmp> que;
        for (auto& i : hash) {
            que.emplace(i);
            if (que.size() > k) {
                que.pop();
            }
        }
        vector<string> ans(k);
        for (int i = k - 1; i >= 0; --i) {
            ans[i] = que.top().first;
            que.pop();
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ypuyu

如果帮助到你,可以请作者喝水~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值