Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
归并排序思想
K个分成2个listNode的合并方法; 二等分,每一份返回合并后的一个ListNode; 合并这两个。
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeKLists (ListNode[] lists) {
return mergeKLists(lists,0 ,lists.length-1 );
}
private ListNode mergeKLists (ListNode[] lists, int s, int e){
if (s==e) return lists[s];
if (s<e){
int q=(s+e)/2 ;
ListNode part1 =mergeKLists(lists,s,q);
ListNode part2=mergeKLists(lists,q+1 ,e);
return mergeTwoLists(part1,part2);
}
else return null ;
}
private ListNode mergeTwoLists (ListNode a, ListNode b){
if (a==null && b==null ) return null ;
if (a==null ) return b;
if (b==null ) return a;
if (a.val<b.val){
a.next=mergeTwoLists(a.next,b);
return a;
}
else {
b.next=mergeTwoLists(a,b.next);
return b;
}
}
}