Ruby's Louvre

每天学习一点点算法

导航

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)

posted on 2020-01-13 22:37  司徒正美  阅读(1094)  评论(0编辑  收藏  举报