-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIntervalListIntersections.java
More file actions
39 lines (31 loc) · 1.18 KB
/
IntervalListIntersections.java
File metadata and controls
39 lines (31 loc) · 1.18 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
package interval;
import java.util.ArrayList;
import java.util.List;
/**
* Description: https://leetcode.com/problems/interval-list-intersections
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class IntervalListIntersections {
public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
List<int[]> intersections = new ArrayList<>();
int firstPointer = 0;
int secondPointer = 0;
while (firstPointer < firstList.length && secondPointer < secondList.length) {
int[] firstInterval = firstList[firstPointer];
int[] secondInterval = secondList[secondPointer];
if (firstInterval[0] <= secondInterval[1] && secondInterval[0] <= firstInterval[1]) {
intersections.add(new int[]{
Math.max(firstInterval[0], secondInterval[0]),
Math.min(firstInterval[1], secondInterval[1])});
}
if (firstInterval[1] < secondInterval[1]) {
firstPointer++;
} else {
secondPointer++;
}
}
return intersections.toArray(new int[0][]);
}
}