最大堆
力扣23
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Comp{
public:
bool operator()(ListNode* node1,ListNode* node2){
return node1->val > node2->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty()) return nullptr;
std::priority_queue<ListNode*,std::vector<ListNode*>,Comp> q;
for(const auto& iter:lists){
if(iter) {
q.push(iter);
}
}
ListNode* dummy=new ListNode(0),*cur=dummy;
while(!q.empty()){
cur->next=q.top();
q.pop();
cur=cur->next;
if(cur->next){
q.push(cur->next);
}
}
return dummy->next;
}
};
仿函数的使用,利用operator进行重载。
//最大堆的使用
class<template T>
std::priority<T,std::vector<T>,std::greater<T>> q;
std::priority<T,std::vector<T>,std::less<T>> q;
lambda函数使用
std::sort(s.begin(),s.end(),[](){
});