注意
return中的 “>” 和 “<” 符号
优先队列中的排序大小与结构体里重载的符号相反
sort()函数中的排序大小与结构体里重载的符号一致
假设node是一个class类以下方式可以实现重载
struct cmp
{
bool operator()(const node &a, const node &b){
return a.val > b.val; // 大于表示小的在前,小根堆
// 对于sort则相反,大于表示大的在前,降序
}
};
priority_queue<node, vector<node>, cmp> pq;
对于set重载,这个const 是必不可少的,少了其中一个都会报错:
struct cmp {
//下面形参的const 和 形参之后的 const都不可缺少,不然不能使用set成员函数
bool operator () (const int& a, const int& b) const {
return a > b;
}
//以下写法均不可行
//bool operator () (int& a, int& b) {}
//bool operator () (int& a, int& b) const {}
//bool operator () (const int& a, const int& b) {}
};
set<int, cmp> st;
// 上面的重载相当于 set<int,greater<int>> st;
class Solution {
public:
int thirdMax(vector<int>& nums) {
for (auto s : nums) st.insert(s);
int i = 0;
int res = INT_MIN;
for (auto s : st) {
if (s >= res) res = s;
i++;
if (i == 3) {
res = s;
break;
}
}
return res;
}
};