题目:
合并 k个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
分析:
和合并两个链表差不多,采用归并排序那种分治思想,两两排序,合并
答案:public static ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0){
return null;
}
return mergeKLists(lists,0,lists.length-1);
}
public static ListNode mergeKLists(ListNode[] lists,int low,int high) {
if(low==high){
return lists[low];
}
int mid=low+((high-low)>>1);
ListNode node1=mergeKLists(lists,low,mid);
ListNode node2=mergeKLists(lists,mid+1,high);
return mergeTwoLists(node1,node2);
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
else if (l2 == null) {
return l1;
}
else if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}
else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}