作者wu10200512 (廷廷)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Wed Jan 31 22:10:32 2024
為啥我sort的判斷函數一定要用靜態函數啊
他報錯叫我加才加的
有沒有人知道
347. Top K Frequent Elements
class Solution {
public:
static bool sortpair(const pair<int, int>& a, const pair<int,int>& b){
return a.second>b.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> mp;
vector<pair<int, int>> v;
for(const int& n:nums){
if(mp.count(n)){
mp[n]++;
}
else{
mp[n]=1;
}
}
for(const auto& p:mp){
v.push_back(p);
}
sort(v.begin(), v.end(), sortpair);
vector<int> ans(k);
for(int i=0; i<k; i++){
ans[i]=v[i].first;
}
return ans;
}
};
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.113.0.229 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1706710234.A.50E.html
推 chuegou: 因為call by class的限制嗎?01/31 22:20
可是都是成員函數應該可以直接叫吧
推 HccrtZ: 那個error google就有了 沒遇過真的沒注意到 :OOO01/31 22:26
所以是leetcode在搞ㄛ
推 SecondRun: 因為sort是static?01/31 22:28
sort是STL的函數應該不是static吧
推 ZooseWu: 這是JAVA嗎01/31 22:28
c++
※ 編輯: wu10200512 (111.250.77.54 臺灣), 01/31/2024 22:34:52
推 tzyysang: 簡單來說 他要吃的不是function 是functor/ 01/31 22:37
→ tzyysang: comparison function object 01/31 22:37
→ tzyysang: 最方便好讀就是寫lambda就好= = 01/31 22:37
推 SecondRun: 那是不是把comparer移到class外面就可以了 01/31 22:39
→ wu10200512: 是不是該學lambda了 01/31 22:45
推 SecondRun: lambda必學的 01/31 22:47