- 时间复杂度是 O(NlogK)O(NlogK)O(NlogK) N 个节点,K 个链表。
- 小根堆可以直接常数时间找到最小值,但是每次 pop 或者 push 需要 logk 的时间。
cpp
class Solution {
public:
struct cmp {
bool operator() ( ListNode *a, ListNode *b ) {
return a->val > b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, cmp> heap;
for ( auto head: lists ) if ( head ) heap.push( head );
ListNode dummy;
ListNode* cur = &dummy;
while ( !heap.empty() ) {
ListNode *minNode = heap.top();
heap.pop();
cur->next = minNode, cur = cur->next;
if ( minNode->next ) heap.push( minNode->next );
}
return dummy.next;
}
};