11//Divide and Conquer method
22
3- public class Solution {
3+ class Solution {
44 public ListNode mergeKLists (ListNode [] lists ) {
5- if (lists == null || lists .length == 0 ) return null ;
6- return sort (lists , 0 , lists .length - 1 );
5+ return merge (lists , 0 , lists .length -1 );
76 }
8-
9- private ListNode sort (ListNode [] lists , int lo , int hi ) {
10- if (lo >= hi ) return lists [lo ];
11- int mid = lo + (hi - lo ) / 2 ;
12- ListNode l1 = sort (lists , lo , mid );
13- ListNode l2 = sort (lists , mid + 1 , hi );
14- return merge (l1 , l2 );
7+
8+ public ListNode merge (ListNode [] lists , int start , int end ){
9+ if (start == end ) return lists [start ];
10+ else if (start < end ){
11+ int mid = start + (end -start )/2 ;
12+ ListNode left = merge (lists , start , mid );
13+ ListNode right = merge (lists , mid +1 , end );
14+ return mergeLists (left , right );
15+ }
16+ else
17+ return null ;
1518 }
16-
17- private ListNode merge (ListNode l1 , ListNode l2 ) {
18- if (l1 == null ) return l2 ;
19- if (l2 == null ) return l1 ;
20- if (l1 .val < l2 .val ) {
21- l1 .next = merge (l1 .next , l2 );
19+
20+ public ListNode mergeLists (ListNode l1 , ListNode l2 ){
21+ if (l1 == null ) return l2 ;
22+ else if (l2 == null ) return l1 ;
23+ else if (l1 .val < l2 .val ){
24+ l1 .next = mergeLists (l1 .next , l2 );
2225 return l1 ;
2326 }
24- l2 .next = merge (l1 , l2 .next );
25- return l2 ;
27+ else {
28+ l2 .next = mergeLists (l1 , l2 .next );
29+ return l2 ;
30+ }
2631 }
2732}
2833
@@ -38,34 +43,34 @@ private ListNode merge(ListNode l1, ListNode l2) {
3843 */
3944class Solution {
4045 public ListNode mergeKLists (ListNode [] lists ) {
41-
46+
4247 ListNode dummy = new ListNode (0 ), cur = dummy ;
43-
48+
4449 if (lists .length == 0 )
4550 return null ;
46-
51+
4752 PriorityQueue <ListNode > minHeap = new PriorityQueue <>(lists .length , new Comparator <ListNode >(){
4853 public int compare (ListNode l1 , ListNode l2 )
4954 {
5055 return l1 .val - l2 .val ;
5156 }
5257 });
53-
58+
5459 for (ListNode list : lists )
5560 if (list != null )
5661 minHeap .offer (list );
57-
62+
5863 while (!minHeap .isEmpty ())
5964 {
6065 ListNode temp = minHeap .poll ();
6166 cur .next = temp ;
6267 if (temp .next != null )
63- minHeap .offer (temp .next );
64-
68+ minHeap .offer (temp .next );
69+
6570 cur = temp ;
6671 }
67-
68- return dummy .next ;
69-
72+
73+ return dummy .next ;
74+
7075 }
7176}
0 commit comments