合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。
样例
给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null
解题思路:
分治法。可以看作先合并左边k/2条,再合并右边k/2条,最后将左右两条合并即可。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
public ListNode mergeKLists(List<ListNode> lists) {
// write your code here
if(lists.size() == 0)
return null;
return merge(lists, 0, lists.size()-1);
}
//分治法归并多条链表
private ListNode merge(List<ListNode> lists, int start, int end){
if(start == end)
return lists.get(start);
int mid = end + ((start - end)>>1);
ListNode leftList = merge(lists, start, mid);
ListNode rightList = merge(lists, mid+1, end);
return mergeTwoLists(leftList, rightList);
}
//归并两条链表
private ListNode mergeTwoLists(ListNode leftList, ListNode rightList){
ListNode dummy = new ListNode(0);
ListNode newNode = dummy;
while(leftList != null || rightList != null){
while(leftList != null && rightList != null){
if(leftList.val < rightList.val){
newNode.next = leftList;
leftList = leftList.next;
}else{
newNode.next = rightList;
rightList = rightList.next;
}
newNode = newNode.next;
}
if(leftList == null){
newNode.next = rightList;
break;
}
if(rightList == null){
newNode.next = leftList;
break;
}
}
return dummy.next;
}
}