File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ //Here two lists are taken at a time and merged. The process is repeated until the last one list in the array.
4+
5+ class Solution {
6+ public ListNode mergeTwoLists (ListNode l1 , ListNode l2 ) {
7+ ListNode h = new ListNode (0 );
8+ ListNode ans =h ;
9+ while (l1 != null && l2 != null ) {
10+ if (l1 .val < l2 .val ) {
11+ h .next = l1 ;
12+ h = h .next ;
13+ l1 = l1 .next ;
14+ } else {
15+ h .next = l2 ;
16+ h = h .next ;
17+ l2 = l2 .next ;
18+ }
19+ }
20+ if (l1 ==null ){
21+ h .next =l2 ;
22+ }
23+ if (l2 ==null ){
24+ h .next =l1 ;
25+ }
26+ return ans .next ;
27+ }
28+ public ListNode mergeKLists (ListNode [] lists ) {
29+ if (lists .length ==0 ){
30+ return null ;
31+ }
32+ int interval = 1 ;
33+ while (interval <lists .length ){
34+ System .out .println (lists .length );
35+ for (int i = 0 ; i + interval < lists .length ; i =i +interval *2 ) {
36+ lists [i ]=mergeTwoLists (lists [i ],lists [i +interval ]);
37+ }
38+ interval *=2 ;
39+ }
40+
41+ return lists [0 ];
42+ }
43+ }
You can’t perform that action at this time.
0 commit comments