Leetcode题目56.合并区间(中等)

题目描述:

给出一个区间的集合,请合并所有重叠的区间。

示例 1:

输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:

输入: [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。

题目解析:

先按首位置进行排序;

接下来,如何判断两个区间是否重叠呢?比如 a = [1,4],b = [2,3]

当 a[1] >= b[0] 说明两个区间有重叠.

但是如何把这个区间找出来呢?

左边位置一定是确定,就是 a[0],而右边位置是 max(a[1], b[1])

所以,我们就能找出整个区间为:[1,4]

代码实现:

    public static int[][] merge(int[][] intervals) {

        List<int[]> res = new ArrayList<>();
        if (intervals == null || intervals.length == 0) {
            return res.toArray(new int[0][]);
        }

        int len = intervals.length;
        //先对所有的集合按照左侧边界进行排序
        Arrays.sort(intervals, Comparator.comparingInt(o -> o[0]));
        int i = 0;
        while (i < len) {
            int left = intervals[i][0];
            int right = intervals[i][1];
            //有重叠,则更新集合的最右边界
            while (i < intervals.length - 1 && intervals[i+1][0] <= right) {
                i++;
                right = Math.max(right, intervals[i][1]);
            }
            res.add(new int[]{left, right});
            i++;
        }

        return res.toArray(new int[0][]);
    }

时间复杂度:

时间复杂度:O(nlogn),除去 sort 的开销,我们只需要一次线性扫描,所以主要的时间开销是排序的 O(nlgn)、

空间复杂度:O(N),借助resres保存结果

原文地址:https://www.cnblogs.com/ysw-go/p/11805298.html