-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathMergeKSortedLists.java
45 lines (43 loc) · 1.26 KB
/
MergeKSortedLists.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//Solution to https://leetcode.com/problems/merge-k-sorted-lists/
//Approach: We use the logic behind merging two sorted lists to merge k number of lists in sorted order.
//Pair up k lists and merge each pair.
//After the first pairing, k lists are merged into k/2 lists with average 2N/k length, then k/4, k/8 and so on.
//This is repeated until we get the final sorted linked list.
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode h = new ListNode(0);
ListNode ans=h;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
h.next = l1;
h = h.next;
l1 = l1.next;
} else {
h.next = l2;
h = h.next;
l2 = l2.next;
}
}
if(l1==null){
h.next=l2;
}
if(l2==null){
h.next=l1;
}
return ans.next;
}
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0){
return null;
}
int interval = 1;
while(interval<lists.length){
System.out.println(lists.length);
for (int i = 0; i + interval< lists.length; i=i+interval*2) {
lists[i]=mergeTwoLists(lists[i],lists[i+interval]);
}
interval*=2;
}
return lists[0];
}
}