跳转至

986.Interval List Intersections

Tags: Medium Two Pointers

Links: https://leetcode.com/problems/interval-list-intersections/v


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:

img

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.


class Solution {
public:
    vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
         vector<vector<int>> res;
        if (A.empty() || B.empty()) return res;

        int lengthA = A.size(), lengthB = B.size();
        int indexA = 0, indexB = 0;
        while (indexA < lengthA && indexB < lengthB) {
            if (A[indexA][1] < B[indexB][0]) ++indexA;
            else if (B[indexB][1] < A[indexA][0]) ++indexB;
            else if (A[indexA][1] <= B[indexB][1]) {
                int left = max(A[indexA][0], B[indexB][0]);
                res.push_back({left, A[indexA][1]});
                ++indexA;
            }
            else if (A[indexA][1] > B[indexB][1]) {
                int left = max(A[indexA][0], B[indexB][0]);
                res.push_back({left, B[indexB][1]});
                ++indexB;
            }
        }

        return res;
    }
};

这道题目其实并不复杂,主要是对于各种可能情况的枚举是否不重不漏。

  • 所以优先判断两种完全不相交的情况,如果是,则靠后的index增加
  • 如果目前index下恰好相交,细分情况其实又会多出两种:

会发现一个规律,真正需要判断的是两个区间的右端点,左端点只需要判断两者中的较大值即可。分类讨论清楚了,代码自然就很容易写出来了。

时间复杂度是O(n + m),空间复杂度是O(n + m),因为需要一个结果数组来存储。