问题:
难度:medium
说明:
阅读理解题。
一般业务算法,玩着玩着就成了阅读理解,看了半天题意,其实意思就是给出一个二维数组 int[N][2] arr,要求找出里面每个一维数组的 i [1] 第二个元素(称为结尾元素),在数组内有没有其他的一维数组 i2 [0] >= i[1] ,有的话写出它的索引多少,没有返回 -1 ,然后 arr 每个元素都要一个结果,所以就返回一个数组作为结果集,并且要求有顺序。
问题链接:https://leetcode.com/problems/find-right-interval/
输入范围:
每一个 i [1] > i[0],并且每个元素 i [0] 都不相等。
输入案例:
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.
我的代码:
阅读理解题,interval 是区间的意识, 然后 i [0] 是起点, i [1] 终点,找每个区间是不是有一个大于或等于他终点值的起点值的区间。
处理方法就是,因为 i [0] 都不相同,所以可以用 hashmap 存储 i [0] 和 i 的位置,明确知道头部和数组位置的索引,然后再把所有 i [0] 都存放到一个数组内进行排序,使用二分法查找一个比 i [0] 大的值,再去 hashmap 获取索引就可以了。
class Solution {
public int[] findRightInterval(int[][] intervals) {
int len = intervals.length, indexSite = len - 1;
int[] res = new int[len], index = new int[len];
// cache
HashMap<Integer, Integer> cache = new HashMap<Integer, Integer>();
for(int i = 0;i < len;i ++) {
cache.put(intervals[i][0], i); // map 暂存
index[i] = intervals[i][0]; // i[0] 存放
}
Arrays.sort(index);
A:for(int i = 0;i < len;i ++) {
int temp = intervals[i][1];
int left = 0, right = indexSite;
while(right > left) { // 二分法处理
int mid = left + right >> 1;
if(index[mid] < temp) left = mid + 1;
else if(index[mid] > temp) right = mid - 1;
else {
res[i] = cache.get(index[mid]);
continue A;
}
}
if(index[right] >= temp) res[i] = cache.get(index[right]);
else if(right + 1 < len) res[i] = cache.get(index[right + 1]);
else res[i] = -1;
}
return res;
}
}