-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_23.java
More file actions
31 lines (27 loc) · 857 Bytes
/
Copy pathP_23.java
File metadata and controls
31 lines (27 loc) · 857 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package leetcode.hard;
import java.util.Comparator;
import java.util.PriorityQueue;
import utils.DataStructures.ListNode;
public class P_23 {
public ListNode mergeKLists(ListNode[] lists) {
final PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.comparingInt(a -> lists[a].val));
final int n = lists.length;
for (int i = 0; i < n; i++) {
if (lists[i] != null) {
pq.offer(i);
}
}
final ListNode res = new ListNode(-1);
ListNode iter = res;
while (!pq.isEmpty()) {
final int curr = pq.remove();
iter.next = lists[curr];
iter = iter.next;
lists[curr] = lists[curr].next;
if (lists[curr] != null) {
pq.offer(curr);
}
}
return res.next;
}
}