Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Divide and Conquer Linked List Heap
分析:题目要求将若干个已排好序的ListNode合并成一个有序的ListNode,可以看做“Merge Two Sorted Lists ”的升级版,关于合并两个有序链表的解决办法请参考(点击打开链接),那么升级为k个有序链表之后,可以考虑使用分治法,将k个链表一分为二,左右各自合并成为一个有序链表后,再将这两个合并成为一个有序链表,对于左右两边的链表,再次一分为二,直到左右为1个链表时直接返回,或2个链表时,采用“Merge Two Sorted Lists ”的方法。具体代码如下:
Java解题:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode mergeKLists(ListNode[] lists) {
int length = lists.length;
if(length==0)
return null;
if(length==1)
return lists[0];
if(length==2)
return mergeTwoLists(lists[0], lists[1]);
return devideLists(0, lists.length-1, lists);
}
public ListNode devideLists(int left,int right,ListNode[] lists){
if(left==right)
return lists[left];
else if(left+1==right)
return mergeTwoLists(lists[left], lists[right]);
else{
int middle=(right+left)/2;
ListNode leftNode = devideLists(left,middle,lists);
ListNode rightNode = devideLists(middle+1,right,lists);
return mergeTwoLists(leftNode,rightNode);
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
else if(l2==null)
return l1;
ListNode l = null;
ListNode head = null;
if(l1.val<l2.val){
head=l=l1;
l1=l1.next;
}
else{
head=l=l2;
l2=l2.next;
}
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
l.next=l1;
l1=l1.next;
}
else{
l.next=l2;
l2=l2.next;
}
l=l.next;
}
if(l1==null){
l.next=l2;
}
else
l.next=l1;
return head;
}