难度主要在时间复杂度上,不能直接k路归并排序,k=10000时,TLE。
应该二路归并,复杂度O(nlogn)
public class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2){
ListNode dummyHead = new ListNode(-1);
ListNode cur = dummyHead;
while(list1 != null && list2 != null){
if (list1.val < list2.val){
cur.next = list1;
list1 = list1.next;
}else{
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
if (list1 == null)
cur.next = list2;
else
cur.next = list1;
return dummyHead.next;
}
public ListNode mergeKLists(ListNode[] lists) {
ListNode head = null;
LinkedList<ListNode> indices = new LinkedList<ListNode>();
for (int i = 0; i < lists.length; i ++){
if (lists[i] != null)
indices.add(lists[i]);
}
if (indices.size() == 0)
return head;
ListNode head1, head2;
while (indices.size() > 1){
head1 = indices.remove();
head2 = indices.remove();
indices.add(mergeTwoLists(head1, head2));
}
return indices.remove();
}
}