Untitled
unknown
plain_text
9 months ago
1.2 kB
5
Indexable
class Solution {
public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
// If either list is empty, return empty list
if (firstList.length == 0 || secondList.length == 0) {
return new int[0][];
}
List<int[]> result = new ArrayList<>();
int i = 0, j = 0;
// Iterate through both lists
while (i < firstList.length && j < secondList.length) {
// Find the intersection start and end
int start = Math.max(firstList[i][0], secondList[j][0]);
int end = Math.min(firstList[i][1], secondList[j][1]);
// If valid intersection, add to result
if (start <= end) {
result.add(new int[]{start, end});
}
// Move the pointer of the interval that ends earlier
if (firstList[i][1] < secondList[j][1]) {
i++;
} else {
j++;
}
}
// Convert list to 2D array
return result.toArray(new int[result.size()][]);
}
}Editor is loading...
Leave a Comment