自定义排序
重写仿函数
struct cmp{ bool operator() ( Node a, Node b ){//默认是less函数 //返回true时,a的优先级低于b的优先级(a排在b的后面) if( a.x== b.x ) return a.y> b.y; return a.x> b.x; } };
struct cmp1{
bool operator () ( int a , int b ){
return a > b;
}
};
struct cmp2{
bool operator ()( int s ,int d ){
return s<d;
}
};
priority_queue<int> q;//默认是从大到小。大顶堆
priority_queue<int, vector<int> ,less<int> >q;//从大到小排序。大顶堆
priority_queue<int, vector<int>, greater<int> >q;//从小到大排序。小顶堆
priority_queue < int , vector<int> , cmp2 > q;//从大到小。大顶堆
priority_queue < int , vector<int> , cmp1 > q;//从小到大。大顶堆
关于priority_queue中元素的比较
模板申明带3个参数:priority_queue<Type, Container, Functional>,其中Type 为数据类型,Container为保存数据的容器,Functional 为元素比较方式。
Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector。
如果把后面2个参数缺省的话,优先队列就是大顶堆(降序)
347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
- It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique.
- You can return the answer in any order
class Solution { public: struct cmp{ bool operator()(pair<int,int>& a,pair<int,int>& b){ if(a.second >= b.second) return true; else return false; } }; vector<int> topKFrequent(vector<int>& nums, int k) { //sort(nums.begin(),nums.end()); vector<int> res; map<int,int> freq2num; for(int i=0;i<nums.size();i++){ freq2num[nums[i]]++; } //默认大顶堆,我们需要小顶堆 priority_queue<pair<int,int>,vector<pair<int,int>>,cmp> p; for(auto iter=freq2num.begin();iter!=freq2num.end();iter++){ if(p.size()<k){ p.push(*iter); }else{ if(p.top().second<iter->second){ p.pop(); p.push(*iter); } } } while(p.size()){ res.push_back(p.top().first); p.pop(); } return res; } };
vector<int> topKFrequent(vector<int>& nums, int k) { vector<int> res; map<int,int> m; for(auto c:nums) { m[c]++; }
//默认大顶堆,我们选前k个。 priority_queue<pair<int,int>> q; //map中iter->first是要返回的数字,ietr->second是数字的个数 for(auto iter=m.begin();iter!=m.end();iter++) { pair<int,int> pr=make_pair(iter->second,iter->first); q.push(pr); } while(k--) { res.push_back(q.top().second); q.pop(); } return res; }