23. Merge k Sorted Lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6
Example 2:
Input: lists = [] Output: []
Example 3:
Input: lists = [[]] Output: []
// 常规做法是正常的两两合并,最终将多个合并成一个。即是先将前两个合并,然后再与第三个合并,再与第四个,第五个。。。直到所有合并结束
// 使用这种二分思想,可以减少遍历的节点数量
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0) return null;
// 从外向内合并首尾两个链表
int rightIndex = lists.length-1;
while(rightIndex > 0){
int low = 0, high = rightIndex;
while(low < high){
lists[low]= merge(lists[low], lists[high]); // 详见合并两个排序列表,https://www.cnblogs.com/MarkLeeBYR/p/16853659.html
low++;
high--;
}
rightIndex=high;
}
return lists[0];
}
例如有8个链表,初始rightIndex=7,
假如有8个链表,初始rightIndex=7
low=0,high=7:
merge(lists[0], lists[7])
merge(lists[1], lists[6])
merge(lists[2], lists[5])
merge(lists[3], lists[4])
rightIndex=3
low=0,high=3:
merge(lists[0], lists[3])
merge(lists[1], lists[2])
rightIndex=1
low=0,high=1:
merge(lists[0], lists[1])
rightIndex=0
浙公网安备 33010602011771号