23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
合并k个有序链表。如果利用mergeTwoLists函数按照顺序逐一合并的话,时间复杂度为O(2n+3n+...+kn)=O(nk^2),会超时。可以采用归并的思想,每次两两合并链表,时间复杂度为O(2n*(k/2)+4n*(k/4)+...+kn*1)=O(nklogk)。
class Solution {
public:
ListNode* mergeTwoLists(ListNode *l1,ListNode *l2){
if(l1==NULL) return l2;
if(l2==NULL) return l1;
if(l1->val<=l2->val){
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}else{
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty()) return NULL;
int len=lists.size();
while(len>1){
for(int i=0;i<len/2;i++){
lists[i]=mergeTwoLists(lists[i],lists[len-i-1]);
}
len=(len+1)/2;
}
return lists.front();
}
};