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