LeetCode 986. Interval List Intersections

Problem

LeetCode 986. Interval List Intersections

1. 题目简述

给出两个闭区间的列表,每个闭区间列表都是以数对的形式顺序排列,且闭区间之间不相连。例如:

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.

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

2. 算法思路

双指针

首先我们看到两个列表的区间很大。。。算了,直接看出来双指针能解决就不假装分析了。

3. 解法

  1. 双指针

class Solution {
    public int[][] intervalIntersection(int[][] A, int[][] B) {
        List<int[]> intersections = new ArrayList();
        int sizeA = A.length, sizeB = B.length, indexA = 0, indexB = 0;

        while (indexA < sizeA && indexB < sizeB) {
            int lo = Math.max(A[indexA][0], B[indexB][0]);
            int hi = Math.min(A[indexA][1], B[indexB][1]);
            if (lo <= hi) {
                intersections.add(new int[]{lo, hi});
            }
            if (hi == A[indexA][1]) {
                indexA++;
            } else {
                indexB++;
            }
        }

        int[][] result = new int[intersections.size()][2];
        for (int i = 0; i < intersections.size(); i++) {
            result[i] = intersections.get(i);
        }

        return result;
    }
}