File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .PriorityQueue ;
2+
3+ /**
4+ * Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode() {}
5+ * ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val;
6+ * this.next = next; } }
7+ */
8+
9+ // TC : PQ -> O(NlogN)
10+ // SC: Linked list -> O(N)
11+ class Solution {
12+
13+ public ListNode mergeKLists (ListNode [] lists ) {
14+ if (lists == null || lists .length == 0 ) {
15+ return null ;
16+ }
17+ PriorityQueue <Integer > pq = new PriorityQueue <>();
18+
19+ for (int i = 0 ; i < lists .length ; i ++) {
20+ while (lists [i ] != null ) {
21+ pq .add (lists [i ].val );
22+ lists [i ] = lists [i ].next ;
23+ }
24+ }
25+ ListNode dummy = new ListNode (0 );
26+ ListNode current = dummy ;
27+ while (!pq .isEmpty ()) {
28+ current .next = new ListNode (pq .poll ());
29+ current = current .next ;
30+ }
31+
32+ return dummy .next ;
33+ }
34+ }
35+
You can’t perform that action at this time.
0 commit comments