leetcode 986. Interval List Intersections

快慢指针法

function intervalIntersection(A, B) {
    if (A == null || A.length == 0 || B == null || B.length == 0) {
        return []
    }

    let ret = [], i = 0, j = 0, startMax, endMin;
    while (i < A.length && j < B.length) {
        startMax = Math.max(A[i][0], B[j][0]);
        endMin = Math.min(A[i][1], B[j][1]);

        if (endMin >= startMax) {
            ret.push([startMax, endMin]);
        }
        if (A[i][1] == endMin)
            i++;
        if (B[j][1] == endMin)
            j++;
    }
    return ret
}

var A = [[0, 2], [5, 10], [13, 23], [24, 25]],
    B = [[1, 5], [8, 12], [15, 24], [25, 26]]
intervalIntersection(A, B)

原文地址:https://www.cnblogs.com/rubylouvre/p/12189760.html