C++优先队列默认是最大堆,所以如果我们要用到最小堆,就需要进行重载来使用。
priority_queue的头文件是<queue>.
1.less和greater,不利用struct进行重载。
priority_queue<int, vector<int>, less<int>>s;//less表示按照递减(从大到小)的顺序插入元素
priority_queue<int, vector<int>, greater<int>>s;//greater表示按照递增(从小到大)的顺序插入元素
less默认最大堆,而greater是最小堆。
2.利用struct进行重载。
struct comp {
comp() {}
~comp() {}
bool operator()(const int a,const int b) {
return a > b;//最小堆,从小到大排序
}
};
priority_queue<int,vector<int>,comp> pq;//pq是最小堆。
而如果把<改为>,就变成了最大堆,从大到小排序。
struct comp {
comp() {}
~comp() {}
bool operator()(const int a,const int b) {
return a < b;//最大堆,从大到小排序。
}
};
相关题目:
leetcode 692:https://leetcode.com/problems/top-k-frequent-words/description/ Top K Frequent Words
leetcode 347 https://leetcode.com/problems/top-k-frequent-elements/description/ Top K Frequent Elements