Skip to content

Commit 96ae455

Browse files
Create 986-Interval-List-Intersections.java
1 parent 274711e commit 96ae455

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//Taken from solution section
2+
//Just two pointer approach
3+
4+
class Solution {
5+
public int[][] intervalIntersection(int[][] A, int[][] B) {
6+
List<int[]> ans = new ArrayList();
7+
int i = 0, j = 0;
8+
9+
while (i < A.length && j < B.length) {
10+
// Let's check if A[i] intersects B[j].
11+
// lo - the startpoint of the intersection
12+
// hi - the endpoint of the intersection
13+
int lo = Math.max(A[i][0], B[j][0]);
14+
int hi = Math.min(A[i][1], B[j][1]);
15+
if (lo <= hi)
16+
ans.add(new int[]{lo, hi});
17+
18+
// Remove the interval with the smallest endpoint
19+
if (A[i][1] < B[j][1])
20+
i++;
21+
else
22+
j++;
23+
}
24+
25+
return ans.toArray(new int[ans.size()][]);
26+
}
27+
}

0 commit comments

Comments
 (0)