题意:
求前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;}
};