|
| 1 | +// Source : https://leetcode.com/problems/interval-list-intersections |
| 2 | +// Author : Dean Shi |
| 3 | +// Date : 2022-01-07 |
| 4 | + |
| 5 | +/*************************************************************************************** |
| 6 | + * You are given two lists of closed intervals, firstList and secondList, where |
| 7 | + * firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of |
| 8 | + * intervals is pairwise disjoint and in sorted order. |
| 9 | + * |
| 10 | + * Return the intersection of these two interval lists. |
| 11 | + * |
| 12 | + * A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x |
| 13 | + * <= b. |
| 14 | + * |
| 15 | + * The intersection of two closed intervals is a set of real numbers that are either |
| 16 | + * empty or represented as a closed interval. For example, the intersection of [1, 3] |
| 17 | + * and [2, 4] is [2, 3]. |
| 18 | + * |
| 19 | + * Example 1: |
| 20 | + * |
| 21 | + * Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24] |
| 22 | + * ,[25,26]] |
| 23 | + * Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] |
| 24 | + * |
| 25 | + * Example 2: |
| 26 | + * |
| 27 | + * Input: firstList = [[1,3],[5,9]], secondList = [] |
| 28 | + * Output: [] |
| 29 | + * |
| 30 | + * Constraints: |
| 31 | + * |
| 32 | + * 0 <= firstList.length, secondList.length <= 1000 |
| 33 | + * firstList.length + secondList.length >= 1 |
| 34 | + * 0 <= starti < endi <= 109 |
| 35 | + * endi < starti+1 |
| 36 | + * 0 <= startj < endj <= 109 |
| 37 | + * endj < startj+1 |
| 38 | + * |
| 39 | + * |
| 40 | + ***************************************************************************************/ |
| 41 | + |
| 42 | +/** |
| 43 | + * @param {number[][]} firstList |
| 44 | + * @param {number[][]} secondList |
| 45 | + * @return {number[][]} |
| 46 | + */ |
| 47 | +var intervalIntersection = function(firstList, secondList) { |
| 48 | + const result = [] |
| 49 | + let firstPt = 0 |
| 50 | + let secondPt = 0 |
| 51 | + let firstItem = firstList[firstPt] |
| 52 | + let secondItem = secondList[secondPt] |
| 53 | + while (firstItem && secondItem) { |
| 54 | + let openingPoint = Math.max(firstItem[0], secondItem[0]) |
| 55 | + let closedPoint = Math.min(firstItem[1], secondItem[1]) |
| 56 | + |
| 57 | + if (closedPoint >= openingPoint) { |
| 58 | + result.push([openingPoint, closedPoint]) |
| 59 | + } |
| 60 | + |
| 61 | + if (firstItem[1] > secondItem[1]) { |
| 62 | + secondItem = secondList[++secondPt] |
| 63 | + } else if (firstItem[1] < secondItem[1]) { |
| 64 | + firstItem = firstList[++firstPt] |
| 65 | + } else { |
| 66 | + firstItem = firstList[++firstPt] |
| 67 | + secondItem = secondList[++secondPt] |
| 68 | + } |
| 69 | + } |
| 70 | + return result |
| 71 | +}; |
0 commit comments