leetcode347.前K个高频元素

先使用map,统计每个字符出现的频率,然后使用优先队列根据字符出现频率存储字符,然后弹出堆中元素,弹出K次完成操作!

如果看不懂本题CPP语法的,可以参考我的另外一篇博客------------->CPP优先队列priority_queue,定义比较器,重载operator()

cpp 复制代码
class less1{
    public:
    bool operator()(const pair<int,int>& p1,const pair<int,int>& p2){
        return p1.second<p2.second;
    }
};

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> m;
        vector<int> ans;
        for(int i=0;i<nums.size();++i){
            m[nums[i]]++;
        }
        priority_queue<pair<int,int>,vector<pair<int,int>>,less1> pq;
        for(const auto& item:m){
            pq.push(item);
        }
        for(int i=0;i<k;++i){
            ans.push_back(pq.top().first);
            pq.pop();
        }
        return ans;
    }
};
相关推荐
猎猎长风3 天前
【数据结构和算法】6. 哈希表
数据结构·算法·哈希表
清羽_ls3 天前
leetcode-哈希表
前端·数据结构·算法·leetcode·哈希表
暖阳华笺8 天前
Leetcode刷题 由浅入深之哈希表——242. 有效的字母异位词
数据结构·c++·算法·leetcode·哈希表
sml259(劳改版)16 天前
数据结构--堆
数据结构·算法·
Tisfy17 天前
LeetCode 3396.使数组元素互不相同所需的最少操作次数:O(n)一次倒序遍历
算法·leetcode·题解·数组·遍历·哈希表
依旧风轻17 天前
使用 Swift 实现 LRU 缓存淘汰策略
缓存·swift·哈希表·lru·双向链表
代码AC不AC19 天前
【数据结构】堆
c语言·数据结构·学习··深度剖析
ゞ 正在缓冲99%…20 天前
leetcode295.数据流的中位数
java·数据结构·算法·leetcode·
Fanxt_Ja1 个月前
【LeetCode】算法详解#2 ---和为k的子数组
java·数据结构·算法·leetcode·idea·哈希表
ゞ 正在缓冲99%…1 个月前
leetcode560.和为k的子数组
leetcode·前缀和·哈希表