-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathProblem_4_Next_Interval.java
More file actions
53 lines (46 loc) · 1.89 KB
/
Problem_4_Next_Interval.java
File metadata and controls
53 lines (46 loc) · 1.89 KB
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
package Heap;
// Problem Statement: Next Interval (hard)
// LeetCode Question: 436. Find Right Interval
import java.util.PriorityQueue;
public class Problem_4_Next_Interval {
class Interval {
int start = 0;
int end = 0;
Interval(int start, int end) {
this.start = start;
this.end = end;
}
}
public int[] findNextInterval(Interval[] intervals) {
int n = intervals.length;
// heap for finding the maximum start
PriorityQueue<Integer> maxStartHeap =
new PriorityQueue<>(n, (i1, i2) -> intervals[i2].start - intervals[i1].start);
// heap for finding the minimum end
PriorityQueue<Integer> maxEndHeap =
new PriorityQueue<>(n, (i1, i2) -> intervals[i2].end - intervals[i1].end);
int[] result = new int[n];
for (int i = 0; i < intervals.length; i++) {
maxStartHeap.offer(i);
maxEndHeap.offer(i);
}
// go through all the intervals to find each interval's next interval
for (int i = 0; i < n; i++) {
// let's find the next interval of the interval which has the highest 'end'
int topEnd = maxEndHeap.poll();
result[topEnd] = -1; // defaults to -1
if (intervals[maxStartHeap.peek()].start >= intervals[topEnd].end) {
int topStart = maxStartHeap.poll();
// find the the interval that has the closest 'start'
while (!maxStartHeap.isEmpty()
&& intervals[maxStartHeap.peek()].start >= intervals[topEnd].end) {
topStart = maxStartHeap.poll();
}
result[topEnd] = topStart;
// put the interval back as it could be the next interval of other intervals
maxStartHeap.add(topStart);
}
}
return result;
}
}