File tree 1 file changed +50
-0
lines changed
1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ # Time Complexity: O(nlogk)
3
+ - n은 lists[i].length의 합
4
+ # Space Complexity: O(k)
5
+ - pq에는 최대 k개의 원소가 저장됨
6
+ */
7
+ /**
8
+ * Definition for singly-linked list.
9
+ * public class ListNode {
10
+ * int val;
11
+ * ListNode next;
12
+ * ListNode() {}
13
+ * ListNode(int val) { this.val = val; }
14
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
15
+ * }
16
+ */
17
+ class Solution {
18
+
19
+ public ListNode mergeKLists (ListNode [] lists ) {
20
+ if (lists .length == 0 ) return null ;
21
+
22
+ PriorityQueue <ListNode > pq = new PriorityQueue <>(new Comparator <ListNode >() {
23
+ @ Override
24
+ public int compare (ListNode n1 , ListNode n2 ) {
25
+ return n1 .val - n2 .val ;
26
+ }
27
+ });
28
+ for (int i = 0 ; i < lists .length ; i ++) {
29
+ if (lists [i ] == null ) continue ;
30
+ pq .offer (lists [i ]);
31
+ }
32
+
33
+ ListNode head = next (pq );
34
+ ListNode curr = head ;
35
+
36
+ while (!pq .isEmpty ()) {
37
+ curr .next = next (pq );
38
+ curr = curr .next ;
39
+ }
40
+
41
+ return head ;
42
+ }
43
+
44
+ private ListNode next (PriorityQueue <ListNode > pq ) {
45
+ ListNode top = pq .poll ();
46
+ if (top == null ) return null ;
47
+ if (top .next != null ) pq .offer (top .next );
48
+ return top ;
49
+ }
50
+ }
You can’t perform that action at this time.
0 commit comments