File tree Expand file tree Collapse file tree 1 file changed +51
-1
lines changed Expand file tree Collapse file tree 1 file changed +51
-1
lines changed Original file line number Diff line number Diff line change 1- class  Solution  {
1+ //  Solution using Min Heap  
2+ //  Time Complexity:         O(n*log(k)) 
3+ //  Extra Space Complexity:  O(k) 
24
5+ class  Solution1  {
36    public  ListNode  mergeKLists (ListNode [] lists ) {
47        Queue <Integer > minHeap  = new  PriorityQueue <>();
58
@@ -22,3 +25,50 @@ public ListNode mergeKLists(ListNode[] lists) {
2225        return  dummy .next ;
2326    }
2427}
28+ 
29+ //  Solution using Iterative Merge Sort 
30+ //  Time Complexity:         O(n*log(k)) 
31+ //  Extra Space Complexity:  O(1) 
32+ 
33+ class  Solution2  {
34+     public  ListNode  mergeKLists (ListNode [] lists ) {
35+         int  size  = lists .length ;
36+         int  interval  = 1 ;
37+         
38+         while (interval  < size ) {
39+             for (int  i  = 0 ; i  < size  - interval ; i  += 2  * interval ) {
40+                 lists [i ] = merge (lists [i ], lists [i  + interval ]);
41+             }
42+             
43+             interval  *= 2 ;
44+         }
45+         
46+         return  size  > 0 ? lists [0 ] : null ;
47+     }
48+     
49+     private  ListNode  merge (ListNode  l1 , ListNode  l2 ) {
50+         ListNode  dummy  = new  ListNode (0 );
51+         ListNode  curr  = dummy ;
52+         
53+         while (l1  != null  && l2  != null ) {
54+             if  (l1 .val  <= l2 .val ) {
55+                 curr .next  = l1 ;
56+                 l1  = l1 .next ;
57+             } else  {
58+                 curr .next  = l2 ;
59+                 l2  = l2 .next ;
60+             }
61+             
62+             curr  = curr .next ;
63+         }
64+         
65+         if  (l1  != null ) {
66+             curr .next  = l1 ;
67+         } else  {
68+             curr .next  = l2 ;
69+         }
70+         
71+         return  dummy .next ;
72+         
73+     }
74+ }
    
 
   
 
     
   
   
          
     
  
    
     
 
    
      
     
 
     
    You can’t perform that action at this time.
  
 
    
  
     
    
      
        
     
 
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments