栈与队列 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;
    }
};
相关推荐
岑梓铭7 分钟前
《考研408数据结构》第六章(6.3 图的遍历)复习笔记
数据结构·笔记·考研··拓扑排序·408
从零开始的代码生活_18 分钟前
C++ stack、queue 与 priority_queue:容器适配器原理与实战
开发语言·c++·后端·学习·算法
晚笙coding19 分钟前
LeetCode 226. 翻转二叉树(Invert Binary Tree)
算法·leetcode·职场和发展
2zcode42 分钟前
项目文档:基于MATLAB低采样率ISAR成像的快速稀疏重建算法研究
开发语言·算法·matlab
哈里沃克1 小时前
编译与链接 - 02
算法
巴糖1 小时前
Embedding了解一些
算法
战族狼魂1 小时前
广东备案大模型超百款
人工智能·算法·大模型·大语言模型
千桐科技1 小时前
🚀 qModel 算法模型平台v1.2.0 开源版发布!Python 模型接入链路全面升级,告别“能跑但上不了线”的尴尬
后端·算法·llm
刘沅2 小时前
LeetCode 93.复原IP地址
算法·面试
阿里技术3 小时前
Agent 评测:方法论与体系设计
大数据·人工智能·算法