436 Find Right Interval

1. Question

Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal to the end point of the interval i, which can be called that j is on the "right" of i.
For any interval i, you need to store the minimum interval j's index, which means that the interval j has the minimum start point to build the "right" relationship for interval i. If the interval j doesn't exist, store -1 for the interval i. Finally, you need output the stored value of each interval as an array.
Note:
  1. 1.
    You may assume the interval's end point is always bigger than its start point.
  2. 2.
    You may assume none of these intervals have the same start point.
Example 1:
1
Input: [ [1,2] ]
2
3
4
Output: [-1]
5
6
7
Explanation: There is only one interval in the collection, so it outputs -1.
Copied!
Example 2:
1
Input: [ [3,4], [2,3], [1,2] ]
2
3
4
Output: [-1, 0, 1]
5
6
7
Explanation: There is no satisfied "right" interval for [3,4].
8
For [2,3], the interval [3,4] has minimum-"right" start point;
9
For [1,2], the interval [2,3] has minimum-"right" start point.
Copied!
Example 3:
1
Input: [ [1,4], [2,3], [3,4] ]
2
3
4
Output: [-1, 2, -1]
5
6
7
Explanation: There is no satisfied "right" interval for [1,4] and [3,4].
8
For [2,3], the interval [3,4] has minimum-"right" start point.
Copied!

2. Implementation

(1) Binary Search
1
/**
2
* Definition for an interval.
3
* public class Interval {
4
* int start;
5
* int end;
6
* Interval() { start = 0; end = 0; }
7
* Interval(int s, int e) { start = s; end = e; }
8
* }
9
*/
10
class Solution {
11
public int[] findRightInterval(Interval[] intervals) {
12
if (intervals == null || intervals.length == 0) {
13
return new int[0];
14
}
15
16
int n = intervals.length;
17
int[] res = new int[n];
18
19
List<Integer> startPoints = new ArrayList<>();
20
Map<Integer, Integer> map = new HashMap<>();
21
22
for (int i = 0; i < n; i++) {
23
startPoints.add(intervals[i].start);
24
map.put(intervals[i].start, i);
25
}
26
27
Collections.sort(startPoints);
28
29
for (int i = 0; i < n; i++) {
30
int start = binarySearch(startPoints, intervals[i].end);
31
32
if (start < intervals[i].end) {
33
res[i] = -1;
34
}
35
else {
36
res[i] = map.get(start);
37
}
38
}
39
return res;
40
}
41
42
public int binarySearch(List<Integer> list, int target) {
43
int start = 0, end = list.size() - 1, mid = 0;
44
45
while (start + 1 < end) {
46
mid = start + (end - start) / 2;
47
48
if (list.get(mid) < target) {
49
start = mid + 1;
50
}
51
else {
52
end = mid;
53
}
54
}
55
56
if (list.get(start) >= target) {
57
return list.get(start);
58
}
59
else {
60
return list.get(end);
61
}
62
}
63
}
Copied!

3. Time & Space Complexity

Binary Search: 时间复杂度O(nlogn), 空间复杂度O(n)