public ListNode mergeKLists(ListNode[] lists) {
int len = lists.length;
if (len == 0) {
return null;
}
// 将n个链表以中间为对称,合并,即合并
while(len>1) {
for (int i=0; i<len/2; i++) {
lists[i] = mergeTwoLists(lists[i], lists[len-1-i]);
}
len = (len+1)/2;
}
return lists[0];
}
// 合并两个链表
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(-1);
ListNode p = head;
while(l1 != null && l2 != null) {
if (l1.val < l2.val) {
p.next = l1;
l1 = l1.next;
} else {
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if (l1 != null) {
p.next = l1;
} else if (l2 != null) {
p.next = l2;
}
return head.next;
}
分治法
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0) return null;
int left = 0; int right = lists.length - 1;
while(right > 0) {
while(left < right) {
lists[left] = merge(lists[left], lists[right]);
left++;
right--;
}
left = 0;
}
return lists[0];
}
private ListNode merge(ListNode node1, ListNode node2) {
ListNode head = new ListNode(0);
ListNode pre = head;
while(node1 != null && node2 != null) {
if(node1.val < node2.val){
pre.next = node1;
node1 = node1.next;
pre = pre.next;
} else {
pre.next = node2;
node2 = node2.next;
pre = pre.next;
}
}
pre.next = node1 == null ? node2 : node1;
return head.next;
}