-
Notifications
You must be signed in to change notification settings - Fork 4
/
FindRightInterval.java
31 lines (27 loc) · 1.01 KB
/
FindRightInterval.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
package com.dbc;
import javafx.util.Pair;
import java.util.Arrays;
import java.util.Comparator;
public class FindRightInterval {
private int search(int left, int right, int target, int[][] intervals) {
while (left < right) {
int mid = (left + right) / 2;
if (intervals[mid][0] >= target) right = mid;
else left = mid + 1;
}
return intervals[left][0] >= target ? intervals[left][1] : -1;
}
public int[] findRightInterval(int[][] intervals) {
int[][] startIntervals = new int[intervals.length][2];
for (int i = 0; i < intervals.length; i++) {
startIntervals[i][0] = intervals[i][0];
startIntervals[i][1] = i;
}
Arrays.sort(startIntervals, Comparator.comparingInt(a -> a[0]));
int[] ans = new int[intervals.length];
for (int i = 0; i < intervals.length; i++) {
ans[i] = search(0, intervals.length - 1, intervals[i][1], startIntervals);
}
return ans;
}
}