栈与队列 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;
    }
};
相关推荐
闲研随记10 小时前
RL算法学习:ArgMaxRL
算法·llm·强化学习·rl
飞Link10 小时前
零基础:离散数据积分与 Python 实现保姆级教程
python·算法
圣保罗的大教堂10 小时前
leetcode 836. 矩形重叠 简单
leetcode
Logic10110 小时前
C语言/数据结构位运算题解:异或XOR找出独特卡片数字——只出现一次的元素
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
郝学胜-神的一滴11 小时前
C++20模板元编程 02:吃透模板基础核心四大核心知识点
开发语言·数据结构·c++·程序人生·软件工程·visual studio
淡海水11 小时前
11-03-Unity-List-T-和Dictionary-TKey-TValue-的性能调优实战
算法·unity·c#·list·dictionary
土司大王11 小时前
LeetCode hot100——394.字符串解码:Java 双栈模拟
java·算法·leetcode
a1879272183111 小时前
【算法】双指针与滑动窗口(三):相向双指针——比较、排除、收缩
算法·leetcode·双指针·滑动窗口·原理·相向双指针·算法讲解
AI 小老六11 小时前
Agent 记忆系统难在取舍
人工智能·算法·架构·agent·memory·harness
大熊背11 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(一)
数码相机·算法·白平衡·色度色域