合并k个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6代码:
两两合并法:
public ListNode mergeKLists(ListNode[] lists) {
ListNode result = null;
for(ListNode listNode : lists){
result = merged(result,listNode);
}
return result;
}
public ListNode merged(ListNode one , ListNode two){
if(one==null)
return two;
if(two==null)
return one;
ListNode head = new ListNode(0);
ListNode tmp = head;
while (one!=null&&two!=null){
if(one.val<=two.val){
tmp.next = one;
ListNode tmpNode = one.next;
one.next = null;
one = tmpNode;
tmp = tmp.next;
}
else {
tmp.next = two;
ListNode tmpNode = two.next;
two.next = null;
two = tmpNode;
tmp = tmp.next;
}
}
if(one!=null){
tmp.next = one;
}
if(two!=null){
tmp.next = two;
}
return head.next;
}归并合并法:
public ListNode mergeKLists(ListNode[] lists) {
if(lists==null||lists.length<=0)
return null;
return merge(lists,0,lists.length-1);
}
public ListNode merge(ListNode[] lists,int start ,int end){
if(start>=end)
return lists[start];
int middle = (start+end)/2;
ListNode one = merge(lists,start,middle);
ListNode two = merge(lists,middle+1,end);
return merged(one,two);
}
public ListNode merged(ListNode one , ListNode two){
if(one==null)
return two;
if(two==null)
return one;
ListNode head = new ListNode(0);
ListNode tmp = head;
while (one!=null&&two!=null){
if(one.val<=two.val){
tmp.next = one;
ListNode tmpNode = one.next;
one.next = null;
one = tmpNode;
tmp = tmp.next;
}
else {
tmp.next = two;
ListNode tmpNode = two.next;
two.next = null;
two = tmpNode;
tmp = tmp.next;
}
}
if(one!=null){
tmp.next = one;
}
if(two!=null){
tmp.next = two;
}
return head.next;
}