leetcode——692.前K个高频单词

思路1

  1. 使用hashmap记录单词频率
  2. 创建vector<string>根据hashmap进行排序
  3. 根据要求对特定的vector进行提取,或者原地erase不需要的元素

代码1

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        //hashmap记录出现次数
        unordered_map<string,int> hashmap;
        for(string item:words)
            hashmap[item]++;
        
        //hashmap转vector<string>
        vector<string> ans;
        for(auto iter=hashmap.begin();iter!=hashmap.end();iter++)
            ans.emplace_back(iter->first);

        //对vector排序
        sort(ans.begin(),ans.end(),[&](const string&p1,const string &p2)->bool{
        if(hashmap[p1]!=hashmap[p2])
            return hashmap[p1] > hashmap[p2];
        else
            return p1 < p2;
        });

        //删除不需要的元素
        ans.erase(ans.begin()+k,ans.end());
        return ans;
    }
};

思路2

  1. 使用hashmap记录单词频率
  2. 创建优先队列进行hashmap排序 元素提取
  3. 创建vector<string>对优先队列第一个元素进行提取

代码2

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        //hashmap记录出现频率
        unordered_map<string, int> cnt;
        for (auto word : words) 
            cnt[word]++;
        //定义cmp函数
        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;
        };
        //根据hashmap和cmp函数 创建优先队列
        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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值