标签:The none called build ice val big find finally
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:
Example 1:
Input: [ [1,2] ]
Output: [-1]
Explanation: There is only one interval in the collection, so it outputs -1.
Example 2:
Input: [ [3,4], [2,3], [1,2] ]
Output: [-1, 0, 1]
Explanation: There is no satisfied "right" interval for [3,4].
For [2,3], the interval [3,4] has minimum-"right" start point;
For [1,2], the interval [2,3] has minimum-"right" start point.
Example 3:
Input: [ [1,4], [2,3], [3,4] ]
Output: [-1, 2, -1]
Explanation: There is no satisfied "right" interval for [1,4] and [3,4].
For [2,3], the interval [3,4] has minimum-"right" start point.
给定一个区间集合S,对于其中的每一个区间s,判断能否在S中找到一个区间t,使得t的左端点大于等于s的右端点。如果能,则找到左端点最小的t。
相当于给定两组数,一组为左端点的集合L,另一组为右端点的集合R,对于R中任意一个点a,在L中找到大于等于a的最小点b。使用二分法查找。
class Solution {
public int[] findRightInterval(int[][] intervals) {
int[] ans = new int[intervals.length];
// 将左端点抽出来和下标绑定,并排序
List<int[]> indices = new ArrayList<>();
for (int i = 0; i < intervals.length; i++) {
indices.add(new int[] { intervals[i][0], i });
}
Collections.sort(indices, (int[] a, int[] b) -> a[0] - b[0]);
for (int i = 0; i < intervals.length; i++) {
int left = 0, right = indices.size() - 1;
int target = intervals[i][1];
while (left < right) {
int mid = (right - left) / 2 + left;
if (indices.get(mid)[0] < target) {
left = mid + 1;
} else {
right = mid;
}
}
if (indices.get(left)[0] >= target) {
ans[i] = indices.get(left)[1];
} else {
ans[i] = -1;
}
}
return ans;
}
}
标签:The none called build ice val big find finally
原文地址:https://www.cnblogs.com/mapoos/p/13313669.html