@@ -17,52 +17,42 @@ private static class ListNode {
1717 }
1818 }
1919
20- private static class ListNodeHolder {
21- final ListNode node ;
22- final int index ;
23-
24- ListNodeHolder (ListNode node , int index ) {
25- this .node = node ;
26- this .index = index ;
20+ // runtime: O(NlgN) where N is number of lists
21+ // space: O(N)
22+ public static ListNode mergeKLists (ListNode [] lists ) {
23+ if (lists == null || lists .length == 0 ) {
24+ return null ;
2725 }
28- }
2926
30- public static ListNode mergeKLists (ListNode [] lists ) {
31- PriorityQueue <ListNodeHolder > heap = new PriorityQueue <>(Comparator .comparingInt (holder -> holder .node .val ));
27+ PriorityQueue <ListNode > heap = new PriorityQueue <>(new Comparator <ListNode >() {
28+ public int compare (ListNode a , ListNode b ) {
29+ return Integer .compare (a .val , b .val );
30+ }
31+ });
3232
33- for (int i = 0 ; i < lists .length ; i ++) {
34- ListNode node = next (lists , i );
33+ for (ListNode node : lists ) {
3534 if (node != null ) {
36- heap .add (new ListNodeHolder ( node , i ) );
35+ heap .add (node );
3736 }
3837 }
39-
38+
4039 ListNode head = null , tail = null ;
41- while (heap .size () > 0 ) {
42- ListNodeHolder holder = heap .poll ();
40+ while (!heap .isEmpty ()) {
41+ ListNode node = heap .poll ();
42+ ListNode next = node .next ;
43+ node .next = null ;
4344 if (head == null ) {
44- head = tail = holder . node ;
45+ head = tail = node ;
4546 } else {
46- tail .next = holder . node ;
47- tail = holder . node ;
47+ tail .next = node ;
48+ tail = node ;
4849 }
49-
50- ListNode next = next (lists , holder .index );
5150 if (next != null ) {
52- heap .add (new ListNodeHolder ( next , holder . index ) );
51+ heap .add (next );
5352 }
5453 }
55-
54+
5655 return head ;
5756 }
5857
59- private static ListNode next (ListNode [] lists , int index ) {
60- ListNode next = lists [index ];
61- if (next != null ) {
62- lists [index ] = next .next ;
63- next .next = null ;
64- }
65-
66- return next ;
67- }
6858}
0 commit comments