合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。
样例
给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
//合并两个排序链表
ListNode *mergeTwoList(ListNode *aList,ListNode *bList){
if(aList==NULL)
return bList;
if(bList==NULL)
return aList;
if(aList->val<bList->val){
aList->next=mergeTwoList(aList->next,bList);
return aList;
}
else{
bList->next=mergeTwoList(bList->next,aList);
return bList;
}
}
//使用归并算法
//分割 递归 合并
ListNode *separateLists(vector<ListNode *> &lists,int a,int b){
if(b-a>1){
int mid=(a+b)/2;
ListNode *q=separateLists(lists,a,mid);
ListNode *p=separateLists(lists,mid+1,b);
return mergeTwoList(p,q);
}
else if(b-a==1){
if(lists[b]==NULL)
return lists[a];
if(lists[a]==NULL)
return lists[b];
return mergeTwoList(lists[a],lists[b]);
}
else if(b==a)
return lists[a];
}
ListNode *mergeKLists(vector<ListNode *> &lists) {
// write your code here
if(lists.empty())
return NULL;
return separateLists(lists,0,lists.size()-1);
}
};