扫描线算法

104 阅读1分钟
  • 作用合并区间

思路

leetcode-cn.com/problems/me… 例题

    1. 标记区间起点和终点 例子:[[1,3],[2,6],[8,10],[15,18]]

起点标记: (1, -1)

终点标记: (3, 1)

-1, 1是为了当起点和终点数字相同时,叠加为0,这样就是完整区间了

    1. 排序所有标记的端点
    1. 遍历
    • 如果is_matched == 0 当前端点设为区间左端点
    • is_matched += boundary[1] 叠加标记
    • 如果等于0 说明到了终点了 (起点和终点数目一样,可以考虑算出区间右端点了)
  • is_matched = 0 表示起点和终点个数一样

细节

-1 和 1 处理区间边界重合情况

[1, 2] [2, 3] 处理为重合还是不重合

-1头,1尾部 重合

反之不重合

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]: 
        boundaries = []
        # 标记
        for interval in intervals:
            boundaries.append((interval[0], -1))
            boundaries.append((interval[1], 1))
        # 排序
        boundaries.sort()
        result = []
        is_matched = 0
        for boundary in boundaries:
            if is_matched == 0:
                left = boundary[0]
            is_matched += boundary[1]
            if is_matched == 0:
                right = boundary[0]
                result.append((left, right))
        return result

java版

class Solution {
    public int[][] merge(int[][] intervals) {
        ArrayList<int[]> tmp = new ArrayList<>();

        for (int i = 0; i < intervals.length; i++) {
            int L = intervals[i][0];
            int R = intervals[i][1];
            tmp.add(new int[]{L, -1});
            tmp.add(new int[]{R, 1});
        }

        tmp.sort((a, b) -> {
            if (a[0] == b[0]) return a[1] - b[1];
            return a[0] - b[0];
        });

        int left = 0;
        int right = 0;
        int isBalanced = 0;
        int size = tmp.size();
        LinkedList<int[]> res = new LinkedList<>();
        for (int i = 0; i < size; i++) {
            if (isBalanced == 0) {
                left = tmp.get(i)[0];
            }
            isBalanced += tmp.get(i)[1];
            if (isBalanced == 0) {
                right = tmp.get(i)[0];
                res.add(new int[]{left, right});
            }
        }
        return res.toArray(new int[res.size()][]);
    }
}

复杂度

排序nlogn 遍历n

空间复杂度n

题目

253.会议室II

leetcode-cn.com/problems/me…

求重叠最多的区间数

759. 员工空闲时间

leetcode-cn.com/problems/em…