自定義排序
sort函數第三個參數compare,為自定義比較函數指針,原型如下:
bool cmp(const Type &a, const Type &b);
如果是想升序,那么就定義當a<b的時候返回true;
如果是想降序,那么就定義當a>b的時候返回true;
注意compare函數寫在類外或者定義為靜態函數
std::sort要求函數對象,或是靜態/全局函數指針,非靜態成員函數指針不能直接傳遞給std::sort。
示例
bool cmp(const pair<int,int> &a, const pair<int,int> &b)
{
return a.second>b.second;
}
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> res;
unordered_map<int, int> countMap;
for (auto item:nums) {
countMap[item]++;
}
vector<pair<int, int>> countVec(countMap.begin(), countMap.end());
// sort(countVec.begin(), countVec.end(), [](const pair<int,int> &a, const pair<int,int> &b){
// return a.second>b.second;
// });
sort(countVec.begin(), countVec.end(), cmp);
for (int i=0;i<k;i++) {
res.push_back(countVec[i].first);
}
return res;
}
};