[英]Can anyone explain how custom comparator works in C++?
問題:給定一個鏈表數組,每個鏈表按升序排序。 將所有鏈表合並為一個排序鏈表並將其返回。
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
我不明白這個自定義比較器如何為最小堆 priority_queue 工作。
/*
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, comp> pq;
for(auto head : lists){
if(head != NULL)
pq.push(head);
}
ListNode* dummy = new ListNode(-1);
ListNode* curr = dummy;
while(!pq.empty()){
curr->next = pq.top();
pq.pop();
curr = curr->next;
ListNode* next = curr->next;
if(next != NULL)
pq.push(next);
}
return dummy->next;
}
struct comp{
bool operator()(ListNode* a, ListNode* b){
return a->val > b->val;
}
};
};
為什么返回的 val 是a->val > b->val
而不是a->val < b->val
std::priority_queue 記錄在 cppreference 上:
可以提供用戶提供的 Compare 來更改順序,例如,使用
std::greater<T>
會導致最小的元素顯示為top()
。
因此,如果您想要一個優先級隊列,您可以在其中彈出最小的元素,它希望您傳遞一個比較器,如果a > b
則返回 true 。
(請注意,您正在泄漏分配給dummy
的 object )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.