Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.

Return the intersection of these two interval lists.

(Formally, 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 is either empty, or can be represented as a closed interval.  For example, the intersection of [1, 3] and [2, 4] is [2, 3].)



Example 1:

[LeetCode] 986. Interval List Intersections_javascript

Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Reminder: The inputs and the desired output are lists of Interval objects, and not arrays or lists.

Note:

  1. ​0 <= A.length < 1000​
  2. ​0 <= B.length < 1000​
  3. ​0 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9​

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.


区间列表的交集。题意是给两组有序的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 }


 

扫描线相关题目

LeetCode 题目总结