Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0)
return null;
//先判断输入
int n=lists.length;
int left=0, right=n-1;
while(right > 0) {
while (left < right) {
lists[left] = merge(lists[left], lists[right]);
left++;
right--;
}
left = 0;
//俩俩进行合并,然后left为0,继续开始合并
}
return lists[0];//合并到最后只剩下一个,并返回
}
public ListNode merge(ListNode n1, ListNode n2) {
ListNode head;
if (n1 == null)
return n2;
if (n2 == null)
return n1;
if (n1.val < n2.val) {
head = n1;
head.next = merge(n1.next, n2);
} else{
head = n2;
head.next = merge(n1, n2.next);
}
return head;
}//这边参照第21题
}