Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路:归并法,主要利用切分简化问题。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
if (lists.length == 1) {
return lists[0];
}
int mid = lists.length / 2;
ListNode[] firstList = Arrays.copyOfRange(lists, 0, mid);
ListNode[] lastList = Arrays.copyOfRange(lists, mid, lists.length);
ListNode l1 = mergeKLists(firstList);
ListNode l2 = mergeKLists(lastList);
return merge2List(l1, l2);
}
private ListNode merge2List(ListNode l1, ListNode l2) {
ListNode head = new ListNode(-1);
ListNode p = head;
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
p.next = l1;
p = p.next;
l1 = l1.next;
} else {
p.next = l2;
p = p.next;
l2 = l2.next;
}
}
if (l1 != null) {
p.next = l1;
}
if (l2 != null) {
p.next = l2;
}
return head.next;
}
}