We should add heads of all k sorted lists. At every instant, you need the minimum of the head of all the k linked list. Once you know the minimum, you can push the node to your answer list, and move over to the next node in that linked list.
The simplest solution is using PriorityQueue as min heap. The elements of the priority queue are ordered according to their natural ordering, or by a comparator provided at the construction time (in this case).
So, we will keep on merging 2 lists at a time, till we have 1 list remaining.
So, initially we will have k/2 lists remaining, then k/4 and finally after some time 1 remaining.
We take O(n) time to merging 2 sorted lists, finally we have time complexity of O(n * log k).
public ListNode mergeKLists(ListNode[] lists) {
if (lists ==null|| lists.length== 0)
returnnull;
int k = lists.length;
while(k>=1){
// pick 1 list from start, another for end.for(int i = 0; i < k/2; i++){
ListNode l1 = lists[i];
ListNode l2 = lists[k-i-1];
lists[i]= mergeTwoLists(l1, l2);
}
// we have to now process remaining k/2 list k = k /2;
}
return lists[0];
}
1
2
3
4
5
6
7
8
9
public ListNode mergeKLists(ListNode[] lists) {
if(lists==null|| lists.length==0) returnnull;
for(int step = 1; step < lists.length; step <<= 1) {
for(int i = 0; i < lists.length-step; i += 2*step)
lists[i]= mergeTwoLists(lists[i], lists[i+step]);
}
return lists[0];
}