扫描线


扫描线

只检查终点和起点

1.Merge Intervals ( LeetCode 56 )

时间88击败 内存99击败

var merge = function(intervals) {
    const result = []

    intervals.sort((a, b) => a[0] - b[0])
    intervals.forEach(item => {
        const len = result.length
        if(!len || result[len - 1][1] < item[0]) {
            result.push(item)
        } else {
            result[len - 1][1] = Math.max(result[len - 1][1], item[1])
        }
    })
    return result
};
// 每次都查找前一个区间与后一个区间是否有重叠

2.Insert Interval ( LeetCode 57 )

var insert = function(intervals, newInterval) {
    const res = []
    let i = 0
    const len = intervals.length

    // 找出 每个框右侧 < new左侧,找出左侧不重叠
    while(i < len && intervals[i][1] < newInterval[0]) {
        res.push(intervals[i])
        i++
    }

    // 找出剩余 每个框左侧 <= new右侧,找出所有重叠,扩宽new左右边界
    while(i < len && intervals[i][0] <= newInterval[1]) {
        newInterval[0] = Math.min(intervals[i][0], newInterval[0])
        newInterval[1] = Math.max(intervals[i][1], newInterval[1])
        i++
    }
    res.push(newInterval)

    // 找出剩余 右侧不重叠
    while(i < len) {
        res.push(intervals[i])
        i++
    }

    return res
};
  1. Remove Interval
  2. Non-overlapping Intervals
  3. Remove Covered Intervals
  4. Data Stream as Disjoint Intervals
  5. Meeting Scheduler (返回最早的common slot,有长度限制)
  6. Interval List Intersections (返回所有的common slot, 无长度限制)
  7. Employee Free Time
  8. The Skyline Problem

文章作者: 罗紫宇
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 罗紫宇 !
  目录