forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1851-Minimum-Interval-to-Include-Each-Query.java
92 lines (73 loc) · 2.57 KB
/
1851-Minimum-Interval-to-Include-Each-Query.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class Query {
int index;
int queryTimeStamp;
int result;
public Query(int index, int queryTimeStamp) {
this.index = index;
this.queryTimeStamp = queryTimeStamp;
this.result = -1; // initially store as -1
}
@Override
public String toString() {
return "[" + index + "," + queryTimeStamp + "," + result + "]";
}
public void setResult(int result) {
this.result = result;
}
}
class IntervalComparator implements Comparator<int[]> {
public static int getSize(int[] interval) {
return (interval[1] - interval[0] + 1);
}
@Override
public int compare(int[] o1, int[] o2) {
int o1Size = getSize(o1), o2Size = getSize(o2);
if (o1Size != o2Size) {
return (o1Size - o2Size);
}
return (o1[1] - o2[1]);
}
}
class Solution {
public int[] minInterval(int[][] intervals, int[] queries) {
// book-keeping & sorting
int numIntervals = intervals.length;
int numQueries = queries.length;
// Sort by start times
Arrays.sort(intervals, (o1, o2) -> (o1[0] - o2[0]));
Query[] sortedQueries = new Query[numQueries];
for (int i = 0; i < numQueries; i++) sortedQueries[i] =
new Query(i, queries[i]);
Arrays.sort(
sortedQueries,
(q1, q2) -> (q1.queryTimeStamp - q2.queryTimeStamp)
);
// algorithm
Comparator<int[]> comparator = new IntervalComparator();
PriorityQueue<int[]> pq = new PriorityQueue<>(comparator);
int idx = 0;
for (Query query : sortedQueries) {
// 1. Keep taking all those queries which have lower starting time than the query time and add them to priority queue
while (
(idx < numIntervals) &&
(query.queryTimeStamp >= intervals[idx][0])
) {
pq.add(intervals[idx]);
idx++;
}
// 2. Keep removing the inconsistent intervals and get the min size interval from priority queue
while (!pq.isEmpty() && (pq.peek()[1] < query.queryTimeStamp)) {
pq.remove();
}
// Now, priority queue must have the consistent & smallest interval
int ans = pq.isEmpty() ? -1 : IntervalComparator.getSize(pq.peek());
query.setResult(ans);
}
// reconversion
int[] results = new int[numQueries];
for (Query query : sortedQueries) {
results[query.index] = query.result;
}
return results;
}
}