欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > Leetcode 347 Top K Frequent Elements

Leetcode 347 Top K Frequent Elements

2024/10/24 18:20:23 来源:https://blog.csdn.net/xxxmmc/article/details/143087949  浏览:    关键词:Leetcode 347 Top K Frequent Elements

题意:
求前k个出现频率最高的元素
首先得到一个频率图这是肯定的,下一步要考虑建立一个堆,堆中保存着前k个频率最大的数字,这个怎么做,可以用customized cmp来做,把数字存进去完事儿。注意这里不用
保存所有的n个数字,只需要k个就好
https://leetcode.com/problems/top-k-frequent-elements/description/

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

class Solution {
public:vector<int> topKFrequent(vector<int>& nums, int k) {unordered_map<int, int> mp;map<int, int> ordered_mp;vector<int> ret;for (auto x: nums) {if(mp.count(x)) {mp[x] += 1;} else {mp[x] = 1;}}auto cmp = [&mp](int a, int b){return mp[a] > mp[b];};priority_queue<int, vector<int>, decltype(cmp)> pq(cmp);for(auto [num,v] : mp) {pq.push(num);if(pq.size() > k) {pq.pop();}}while(pq.size()) {ret.push_back(pq.top());pq.pop();}return ret;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com