栈与队列 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;
    }
};
相关推荐
IronMurphy4 小时前
【算法五十七】146. LRU 缓存
算法·缓存
Irissgwe5 小时前
数据结构-栈和队列
数据结构·c++·c·栈和队列
两片空白5 小时前
数据容器集合set/frozenset
数据结构
凌波粒5 小时前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
liulilittle5 小时前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
浦信仿真大讲堂5 小时前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
点云侠5 小时前
PCL 生成三棱锥点云
c++·算法·最小二乘法
代码中介商6 小时前
跳表:高效查找的链表黑科技
数据结构
兰令水6 小时前
leecodecode【面试150】【2026.6.13打卡-java版本】
java·算法·leetcode
临沂堇6 小时前
刷题日志 | Leetcode Hot 100 哈希
算法·leetcode·哈希算法