Minimum Interval to Include Each Query LeetCode solution in Java

1
class Solution {
2
public int[] minInterval(int[][] intervals, int[] queries) {
3
// sort intervals
4
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
5
// add [index,query]
6
int[][] q = new int[queries.length][2];
7
for (int i = 0; i < queries.length; i++) {
8
q[i][0] = i;
9
q[i][1] = queries[i];
10
}
11
// sort the queries by query val
12
Arrays.sort(q, (a, b) -> a[1] - b[1]);
13
// store the minimum intervals in the priority queue, min heap
14
Queue<int[]> pq = new PriorityQueue<>((a, b) -> (a[1] - a[0]) - (b[1] - b[0]));
15
int[] result = new int[queries.length];
16
int j = 0;
17
for (int i = 0; i < q.length; i++) {
18
int index = q[i][0];
19
int val = q[i][1];
20
// if start is less than query val, then add to pq
21
while (j < intervals.length && intervals[j][0] <= val) pq.offer(intervals[j++]);
22
// anything which has the end lesser than the val then remove it
23
while (!pq.isEmpty() && pq.peek()[1] < val) pq.poll();
24
// add difference to the result
25
result[index] = pq.isEmpty() ? -1 : pq.peek()[1] - pq.peek()[0] + 1;
26
}
27
return result;
28
}
29
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0