-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterval_List_Intersections.java
More file actions
70 lines (52 loc) · 2.04 KB
/
Copy pathInterval_List_Intersections.java
File metadata and controls
70 lines (52 loc) · 2.04 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
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].
Example 1:
Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Example 2:
Input: firstList = [[1,3],[5,9]], secondList = []
Output: []
Constraints:
0 <= firstList.length, secondList.length <= 1000
firstList.length + secondList.length >= 1
0 <= starti < endi <= 109
endi < starti+1
0 <= startj < endj <= 109
endj < startj+1
*/
import java.util.*;
class Inteval_List_Intersections {
public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
List<int[]> ans = new ArrayList<>();
int n = firstList.length;
int m = secondList.length;
int i = 0;
int j = 0;
while (i < n && j < m) {
int start1 = firstList[i][0];
int end1 = firstList[i][1];
int start2 = secondList[j][0];
int end2 = secondList[j][1];
if (start1 <= start2) {
if (end1 >= start2) {
int s = Math.max(start1, start2);
int e = Math.min(end1, end2);
ans.add(new int[]{s, e});
}
} else if (end2 >= start1) {
int s = Math.max(start1, start2);
int e = Math.min(end1, end2);
ans.add(new int[]{s, e});
}
if (end1 < end2) {
i++;
} else {
j++;
}
}
return ans.toArray(new int[ans.size()][]);
}
}