File tree Expand file tree Collapse file tree 1 file changed +21
-33
lines changed Expand file tree Collapse file tree 1 file changed +21
-33
lines changed Original file line number Diff line number Diff line change 3
3
* public class ListNode {
4
4
* int val;
5
5
* ListNode next;
6
- * ListNode(int x) { val = x; }
6
+ * ListNode() {}
7
+ * ListNode(int val) { this.val = val; }
8
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
7
9
* }
8
10
*/
9
11
class Solution {
10
- public ListNode mergeKLists (ListNode [] lists ) {
11
- if (lists .length == 0 ) {
12
- return null ;
13
- }
14
-
15
- PriorityQueue <ListNode > queue = new PriorityQueue <>(lists .length , new Comparator <ListNode >() {
16
- @ Override
17
- public int compare (ListNode o1 , ListNode o2 ) {
18
- return o1 .val - o2 .val ;
19
- }
20
- });
21
-
22
- for (int i = 0 ; i < lists .length ; i ++) {
23
- if (lists [i ] != null ) {
24
- queue .add (lists [i ]);
25
- }
26
- }
27
-
28
- ListNode head = new ListNode (0 );
29
- ListNode p = head ;
30
-
31
- while (!queue .isEmpty ()) {
32
- ListNode node = queue .poll ();
33
- p .next = node ;
34
- if (node .next != null ) {
35
- queue .add (node .next );
36
- }
37
-
38
- p = p .next ;
39
- }
40
-
41
- return head .next ;
12
+ public ListNode mergeKLists (ListNode [] lists ) {
13
+ PriorityQueue <ListNode > pq = new PriorityQueue <>((a , b ) -> a .val - b .val );
14
+ for (ListNode listNode : lists ) {
15
+ if (listNode != null ) {
16
+ pq .add (listNode );
17
+ }
42
18
}
19
+ ListNode dummy = new ListNode (0 );
20
+ ListNode curr = dummy ;
21
+ while (!pq .isEmpty ()) {
22
+ ListNode removed = pq .remove ();
23
+ curr .next = new ListNode (removed .val );
24
+ curr = curr .next ;
25
+ if (removed .next != null ) {
26
+ pq .add (removed .next );
27
+ }
28
+ }
29
+ return dummy .next ;
30
+ }
43
31
}
You can’t perform that action at this time.
0 commit comments