1. problem description
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
2. solution
struct compareFn {
bool operator() ( ListNode *n1, ListNode *n2 ) {
return n1->val > n2->val;
}
};
class Solution {
public:
ListNode* mergeKLists( vector<ListNode*> &lists ) {
if( lists.size() == 0 ) return nullptr;
priority_queue< ListNode*, vector<ListNode*>, compareFn > minHeap;
for( int i=0; i < lists.size(); i++ ) {
if( lists[i] ) minHeap.push( lists[i] );
}
ListNode *head = new ListNode(0); // dummy head
ListNode *curr = head;
while( !minHeap.empty() ) {
curr->next = minHeap.top();
curr = curr->next;
minHeap.pop();
if( curr->next ) {
// means this link list has more elements
minHeap.push( curr->next );
}
}
return head->next;
}
};