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: []
Example 3:
Input: firstList = [], secondList = [[4,8],[10,12]] Output: []
Example 4:
Input: firstList = [[1,7]], secondList = [[3,10]] Output: [[3,7]]
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
区间列表的交集。
题意是给两组有序的 intervals of intervals,请将他们的重叠部分合并成一组。这个题目依然是用到扫描线的思想,同时也用到了追击型的双指针。需要创建两个指针 i 和 j,分别记录 interval A 和 B 的位置。试图合并两边的 interval 的时候,依然采取 [start, end],start 两边取大,end 两边取小的原则(11,12行)。判断到底是 i++ 还是 j++ 是通过判断当前遍历到的 interval 谁的 end 小,谁小谁的指针就++(16 - 20行)。
时间O(n)
空间O(1)
JavaScript实现
1 /** 2 * @param {number[][]} A 3 * @param {number[][]} B 4 * @return {number[][]} 5 */ 6 var intervalIntersection = function (A, B) { 7 let i = 0; 8 let j = 0; 9 let res = []; 10 while (i < A.length && j < B.length) { 11 let maxStart = Math.max(A[i][0], B[j][0]); 12 let minEnd = Math.min(A[i][1], B[j][1]); 13 if (maxStart <= minEnd) { 14 res.push([maxStart, minEnd]); 15 } 16 if (A[i][1] < B[j][1]) { 17 i++; 18 } else { 19 j++; 20 } 21 } 22 return res; 23 };
Java实现
1 class Solution { 2 public int[][] intervalIntersection(int[][] A, int[][] B) { 3 int i = 0; 4 int j = 0; 5 List<int[]> res = new ArrayList(); 6 while (i < A.length && j < B.length) { 7 int low = Math.max(A[i][0], B[j][0]); 8 int high = Math.min(A[i][1], B[j][1]); 9 if (low <= high) { 10 res.add(new int[] { low, high }); 11 } 12 if (A[i][1] < B[j][1]) { 13 i++; 14 } else if (A[i][1] == B[j][1]) { 15 i++; 16 j++; 17 } else { 18 j++; 19 } 20 } 21 // int[][] resArray = new int[res.size()][]; 22 return res.toArray(new int[res.size()][]); 23 } 24 }