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: []
可以使用类似 Merge Sort 的方式归并。
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists==null || lists.length<1) return null;
return mergeKLists(lists, lists.length);
}
//num 表示剩余未 merge 的 List ,仅剩 1 个的时候返回
private ListNode mergeKLists(ListNode[] lists, int num) {
if(num==1) return lists[0];
int index=0;
for(int i=0;i<num-1;i=i+2){
lists[index++] = merge2(lists[i], lists[i+1]);
}
if(num%2==1){
lists[index++]=lists[num-1];
}
return mergeKLists(lists, index);
}
//归并2个 List
private ListNode merge2(ListNode l1, ListNode l2){
ListNode head = new ListNode();
ListNode t = head;
while(l1!=null && l2!=null){
if(l1.val<l2.val){
t.next=l1;
l1=l1.next;
} else {
t.next=l2;
l2=l2.next;
}
t=t.next;
}
if(l1==null) {
t.next=l2;
} else {
t.next=l1;
}
return head.next;
}
}