栈与队列 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;
    }
};
相关推荐
稚辉君.MCA_P8_Java1 小时前
Gemini永久会员 Java实现的暴力递归版本
java·数据结构·算法
冯诺依曼的锦鲤1 小时前
算法练习:差分
c++·学习·算法
有意义2 小时前
栈数据结构全解析:从实现原理到 LeetCode 实战
javascript·算法·编程语言
鹿鹿鹿鹿isNotDefined2 小时前
逐步手写,实现符合 Promise A+ 规范的 Promise
前端·javascript·算法
封奚泽优2 小时前
下降算法(Python实现)
开发语言·python·算法
im_AMBER2 小时前
算法笔记 16 二分搜索算法
c++·笔记·学习·算法
高洁012 小时前
【无标具身智能-多任务与元学习】
神经网络·算法·aigc·transformer·知识图谱
leoufung2 小时前
逆波兰表达式 LeetCode 题解及相关思路笔记
linux·笔记·leetcode
识醉沉香3 小时前
广度优先遍历
算法·宽度优先
中國龍在廣州3 小时前
现在人工智能的研究路径可能走反了
人工智能·算法·搜索引擎·chatgpt·机器人