2021.05.12寻找右区间
(题目来源:leetcode)
题目描述
有一组区间,定义区间i的“右区间”为这组区间中起点比区间i的终点大的区间,并且起点离区间i终点最近。
思路
思路1 排序
可通过排序后做
思路1 代码
public int[] findRightInterval(int[][] inls) {
int n = inls.length;
int[] res = new int[n];
Arrays.fill(res, -1);
Inl[] inl = new Inl[n];
for(int i = 0; i < n; i++) inl[i] = new Inl(inls[i][0], inls[i][1],i);
Arrays.sort(inl);
for(int i = 0; i < n; i++) {
for(int j = i+1; j < n; j++) {
if(inl[j].s >= inl[i].e) {
res[inl[i].i] = inl[j].i;
break;
}
}
}
return res;
}
class Inl implements Comparable<Inl>{
int s,e,i;
public Inl(int s, int e, int i) {
super();
this.s = s;
this.e = e;
this.i = i;
}
public int compareTo(Inl o) { //按照起点升序排列
return this.s-o.s;
}
}
思路2 Hashmap
public int[] findRightInterval_hashMap(int[][] inls) {
int n = inls.length;
int[] res = new int[n];
Map<int[],Integer> map = new HashMap<int[], Integer>();
for(int i = 0; i < n; i++) map.put(inls[i], i);
Arrays.sort(inls, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
return o1[0]-o2[0];
}
});
for(int i = 0; i < n; i++) {
res[map.get(inls[i])] = -1;
for(int j = i; j < n; j++) {
if(inls[i][1] <= inls[j][0]) {
res[map.get(inls[i])] = map.get(inls[j]);
break;
}
}
}
return res;
}
本文提供了一道LeetCode上的编程题目“寻找右区间”的两种解决方案:一种使用排序的方法,另一种采用Hashmap来实现。排序方法通过遍历并比较区间的起点和终点来找到符合条件的右区间;而Hashmap方法则是先将区间与索引映射存储,再进行排序查找。
1万+

被折叠的 条评论
为什么被折叠?



