合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6
package LeetCode_5_14;
/**
* @author : caoguotao
* @date 创建时间:2019年5月14日 下午5:24:02
* @version 1.0
* @parameter
* @since
* @return
*/
public class Solution23 {
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public static void main(String[] args) {
ListNode[] lists = new ListNode[3];
ListNode n11 = new ListNode(1);
ListNode n12 = new ListNode(4);
ListNode n13 = new ListNode(5);
n11.next = n12;
n12.next = n13;
n13.next = null;
ListNode n21 = new ListNode(1);
ListNode n22 = new ListNode(3);
ListNode n23 = new ListNode(4);
n21.next = n22;
n22.next = n23;
n23.next = null;
ListNode n31 = new ListNode(2);
ListNode n32 = new ListNode(6);
n31.next = n32;
n32.next = null;
lists[0] = n11;
lists[1] = n21;
lists[2] = n31;
ListNode res = mergeKLists(lists);
while(res != null) {
System.out.println(res.val);
res = res.next;
}
}
public static ListNode mergeKLists(ListNode[] lists) {
if(lists.length == 0)
return null;
if(lists.length == 1)
return lists[0];
if(lists.length == 2) {
return mergeTwoLists(lists[0], lists[1]);
}
int mid = lists.length / 2;
ListNode[] front = new ListNode[mid];
for(int i = 0; i < mid; i++) {
front[i] = lists[i];
}
ListNode[] rear = new ListNode[lists.length - mid];
for(int i = mid, j = 0; i < lists.length; i++, j++) {
rear[j] = lists[i];
}
return mergeTwoLists(mergeKLists(front), mergeKLists(rear));
}
private static ListNode mergeTwoLists(ListNode front, ListNode rear) {
if(front == null)
return rear;
if(rear == null)
return front;
ListNode head = null;
if(front.val <= rear.val) {
head = front;
head.next = mergeTwoLists(front.next, rear);
}
else {
head = rear;
head.next = mergeTwoLists(front, rear.next);
}
return head;
}
}