栈与队列 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;
    }
};
相关推荐
wzdark1 分钟前
分块思想在算法优化中的实践与应用4
算法
Because_of_Her19 分钟前
dfs-洪水填充技巧
笔记·算法·深度优先·洪水填充
小静AI工程实验室21 分钟前
RSA 算法详解:从模幂原理到 OAEP 加密、PSS 签名与 Python 实验
python·算法
xzal1229 分钟前
GESP Python笔记
笔记·python·算法
wzdark30 分钟前
算法中的记忆化思想与重复子问题优化4
算法
Discipline10291 小时前
流水线运行是否正随时间变得更加集中?
算法
Logic1011 小时前
C语言/数据结构位运算题解:异或XOR找出书柜中编号只出现一次的那一层——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
lzhdim1 小时前
C#不为人知的10个魔法特性:资深开发者也会震惊的底层奥秘
java·前端·javascript·算法·c#
weixin_307779131 小时前
C++代码实现MATLAB中的pade函数功能
开发语言·c++·算法·matlab
smj2302_796826521 小时前
解决leetcode第4064题至多一次取反能被k整除的最长子数组II
python·算法·leetcode