Skip to content

Commit d2c3978

Browse files
Merge pull request #173 from niranjana687/patch-3
Create MergeKSortedLists.java
2 parents 3ccdba1 + 7267348 commit d2c3978

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

LeetCode/MergeKSortedLists.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//Solution to https://leetcode.com/problems/merge-k-sorted-lists/
2+
//Approach: We use the logic behind merging two sorted lists to merge k number of lists in sorted order.
3+
//Pair up k lists and merge each pair.
4+
//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.
5+
//This is repeated until we get the final sorted linked list.
6+
7+
class Solution {
8+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
9+
ListNode h = new ListNode(0);
10+
ListNode ans=h;
11+
while (l1 != null && l2 != null) {
12+
if (l1.val < l2.val) {
13+
h.next = l1;
14+
h = h.next;
15+
l1 = l1.next;
16+
} else {
17+
h.next = l2;
18+
h = h.next;
19+
l2 = l2.next;
20+
}
21+
}
22+
if(l1==null){
23+
h.next=l2;
24+
}
25+
if(l2==null){
26+
h.next=l1;
27+
}
28+
return ans.next;
29+
}
30+
public ListNode mergeKLists(ListNode[] lists) {
31+
if(lists.length==0){
32+
return null;
33+
}
34+
int interval = 1;
35+
while(interval<lists.length){
36+
System.out.println(lists.length);
37+
for (int i = 0; i + interval< lists.length; i=i+interval*2) {
38+
lists[i]=mergeTwoLists(lists[i],lists[i+interval]);
39+
}
40+
interval*=2;
41+
}
42+
43+
return lists[0];
44+
}
45+
}

0 commit comments

Comments
 (0)