692. Top K Frequent Words(medium)

这篇博客探讨了如何在C++中找到给定单词列表中最常出现的k个单词。首先,通过创建一个映射来计算每个单词的频率,然后利用优先队列(最小堆)来实现按频率降序并字母升序排列的结果。这种方法在处理大量数据时,时间和空间效率相对较高。
摘要由CSDN通过智能技术生成
  1. Top K Frequent Words
    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.
  • 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.

1.使用map存储,然后将键值对存到向量,对向量进行排序。

    static bool cmp(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> topKFrequent(vector<string>& words, int k) {
        unordered_map<string,int>counts;
        
        vector<string>res;
        for(int i=0;i<words.size();i++){
            counts[words[i]]++;
        }
        vector<pair<string,int>>v(counts.begin(),counts.end());
        sort(v.begin(),v.end(),cmp);
        for(int i=0;i<k;i++){
            res.push_back(v[i].first);
        }
        return res;
    }

官方题解写的更为精巧,但是提交之后时间和空间的开销都稍大
匿名函数那里我没看懂。。。。。

    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string,int>counts;
        for(auto x:words){
            counts[x]++;
        }
        vector<string>res(words.size());
        for(auto &[key,value]:counts){
            res.emplace_back(key);
        }
        sort(res.begin(),res.end(),[&](const string &a,const string &b)->bool{
            return counts[a]>counts[b]||counts[a]==counts[b]&&a<b;
        });
        res.erase(res.begin()+k,res.end());
        return res;
    }

2.优先队列
第一次接触优先队列,对堆还很不熟悉
依旧还没看懂。。。。。。

    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string,int>counts;
        int n=words.size();
        for(int i=0;i<n;i++){
            counts[words[i]]++;
        }
         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 : counts) {
            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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值