986. Interval List Intersections

You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.

Return the intersection of these two interval lists.

A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.

The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].

设置两个指针,分别指向两个intervals的头部。
循环,相交的left等于两者左端的较大值。right等于两者右端的较小值。
只有在left小于right时,两个interval才相交,填入列表。
然后更新两个interval中右端较小的指针。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
List<int[]> ans = new ArrayList();
int i = 0;
int j = 0;

while(i < firstList.length && j < secondList.length){
int left = Math.max( firstList[i][0], secondList[j][0] );
int right = Math.min( firstList[i][1], secondList[j][1] );
if(left <= right){
ans.add(new int[]{left, right});
}
if(firstList[i][1] < secondList[j][1]) i++;
else j++;

}

int[][] ret = new int[ans.size()][2];
ans.toArray(ret);
return ret;
}
}
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
int i = 0;
int j = 0;
ArrayList<int[]> ans = new ArrayList();
int[] holdA;
int[] holdB;

while(i < firstList.length && j < secondList.length){
holdA = firstList[i];
holdB = secondList[j];

int[] arr = new int[2];

if(holdA[0] <= holdB[0] && holdA[1] >= holdB[1]){
ans.add(holdB);
j++;
}
else if(holdA[0] >= holdB[0] && holdA[1] <= holdB[1]){
ans.add(holdA);
i++;
}
else if(holdA[0] <= holdB[0] && holdA[1] >= holdB[0]){
arr[0] = holdB[0];
arr[1] = holdA[1];
ans.add(arr);
i++;
}
else if(holdA[0] >= holdB[0] && holdB[1] >= holdA[0]){
arr[0] = holdA[0];
arr[1] = holdB[1];
ans.add(arr);
j++;
}
else if(holdA[1] <= holdB[1]){
i++;
}
else{
j++;
}
}
int[][] ret = new int[ans.size()][2];
ans.toArray(ret);
return ret;
}
}
Author

Xander

Posted on

2022-04-19

Updated on

2022-04-19

Licensed under

Comments