栈与队列 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;
    }
};
相关推荐
Keven_1114 分钟前
算法札记:有限差分
算法
忙里偷闲学python18 分钟前
GK2A 林火蔓延预报算法说明
算法
我是伪码农27 分钟前
11.21程序设计
数据结构·算法
Tisfy1 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6171 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
羊在吃青草2 小时前
C语言之数组
c语言·数据结构
灯澜忆梦2 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法
专注仿真2 小时前
达梦数据库 SQL 优化实战:从执行计划到索引、统计信息与参数调优
数据结构·数据库·数据库开发·数据库架构
Shaoshing3 小时前
LeetCode100 155.最小栈
java·数据结构·算法