等级:困难
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
输入:lists = [[1,4,5],[1,3,4],[2,6]] 输出:[1,1,2,3,4,4,5,6]
思路分析:
1、将k个链表配对并将同一对中的链表进行合并(采用顺序合并的方法)
2、第一轮合并后,k个链表合并成了 k/2 个链表,平均长度 2n/k ,然后是 k/4、k/8...等等
3、重复这一过程,知道获取最终的有序链表
图解
代码实现:
public ListNode mergeKLists(ListNode[] lists) {
return mergeList(lists,0,lists.length -1);
}
// 分治进行链表两两合并
public ListNode mergeList(ListNode[] lists,int l,int r){
if(l == r)
return lists[l];
if(l > r)
return null;
int mid = l + (r-l)/2;
return merge(mergeList(lists,l,mid),mergeList(lists,mid+1,r));
}
// 合并两个链表,对比合并
public ListNode merge(ListNode head1,ListNode head2){
if(head1 == null)
return head2;
if(head2 == null)
return head1;
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
while(head1 != null && head2 != null){
if(head1.val <= head2.val){
cur.next = head1;
head1 = head1.next;
}
else{
cur.next = head2;
head2 = head2.next;
}
cur = cur.next;
}
cur.next = (head1 == null) ? head2 : head1;
return dummy.next;
}