leetcode/C++常用

本文介绍了如何在C++中使用unordered_map统计字符串频率,通过优先队列实现top K最频繁字符串,并讨论了如何利用map进行key或value排序。重点讲解了LeetCode题目692的解决方案。

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

1.string和int之间的相互转换

2.优先队列的插入数据和进行排序

//leetcode-692
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;
        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;
    }
};

3.map按照key或者value进行排序

// leetcode-692
class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> record;
        vector<string> res;
        for (auto word : words) {
            record[word]++;
        }
        vector<pair<string, int>> vectorRecord;
        // map不能直接按照key或者value进行排序,必须放置在vector中进行排序
        for (auto elem : record) {
            vectorRecord.push_back(make_pair(elem.first, elem.second));
        }
        sort(vectorRecord.begin(), vectorRecord.end(), cmp);
        int x = k;
        for (auto elem : vectorRecord) {
            if (x > 0) {
                res.push_back(elem.first);
            }
            x--;
        }
        return res;
    }
    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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值