栈与队列 Leetcode 347 前k个高频元素

栈与队列 Leetcode 347 前k个高频元素

Leetcode 347

灵活运用C++库函数,使用匿名函数排序,sort可以替换为快排实现(面试感觉可能会手撕,机考直接使用sort)

cpp 复制代码
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        map<int, int> num_f;
        for(int i = 0; i < nums.size(); i++){
            num_f[nums[i]]++;
        }
        vector<pair<int, int>> num_f_vec;
        map<int, int>::iterator it;
        for(it = num_f.begin(); it != num_f.end(); it++){
            // push_back()是创建对象后在复制到vector末尾,而emplace_back是就地构建对象没有复制和移动的操作,提高复杂对象到vector的性能
            num_f_vec.emplace_back(it->first, it->second);
        }
        sort(num_f_vec.begin(), num_f_vec.end(), [](pair<int, int>& a, pair<int, int>& b){
            return a.second > b.second;
        });
        vector<int> res;
        for(int i = 0; i < k; i++){
            res.push_back(num_f_vec[i].first);
        }
        return res;
    }
};
相关推荐
smj2302_796826524 小时前
解决leetcode第3943题递增后的数对数量
数据结构·python·算法·leetcode
炽烈小老头5 小时前
【每天学习一点算法 2026/05/25】矩阵中的最长递增路径
学习·算法·矩阵
叁散6 小时前
实验报告:5G 仿真环境与基本链路模拟
算法
从负无穷开始的三次元代码生活6 小时前
算法零碎灵感点分享
算法
梓䈑6 小时前
【算法题攻略】快速排序 和 归并排序
数据结构·c++·排序算法
染指11106 小时前
9.LangChain框架(实现RAG)
数据库·人工智能·算法·机器学习·ai·大模型
大数据三康6 小时前
在spyder进行的遗传算法练习
开发语言·python·算法
Gene_20226 小时前
轮式底盘的微分平坦
算法
医用门7 小时前
医院用门一线品牌
leetcode
吴佳浩7 小时前
现代多模态大模型的核心基础:Unified Self-Attention
人工智能·算法·llm