IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    56. Merge Intervals

    10k发表于 2023-05-08 00:00:00
    love 0

    Question

    Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

    Example 1:

    Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
    Output: [[1,6],[8,10],[15,18]]
    Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
    

    Algorithm

    For this question, we need to sort the array intervals by their start.(interval[0]) by full sort.

    Why do this? For example, after sorting, all the start will have an order, and if the next one's start is larger than the previous one's end, that means they have no overlap; if one's start is smaller than it's previous one's end, that mean they have overlaps and needs to be merged. And the larger end of them will be treat as the new end.

    Code

    class Solution {
        public int[][] merge(int[][] intervals) {
            Arrays.sort(intervals, (a, b) -> (a[0] - b[0]));
            List<int[]> res = new ArrayList<>();
            int start = intervals[0][0];
            int end = intervals[0][1];
            for (int i = 0; i < intervals.length; i++) {
                if (intervals[i][0] > end) {
                    res.add(new int[]{start, end});
                    start = intervals[i][0];
                    end = intervals[i][1];
                } else {
                    end = Math.max(end, intervals[i][1]);
                }
                if (i == intervals.length - 1) {
                    res.add(new int[]{start, end});
                }
            }
            int[][] result = new int[res.size()][2];
            for (int i = 0; i < res.size(); i++) {
                result[i][0] = res.get(i)[0];
                result[i][1] = res.get(i)[1];
            }
            return result;
        }
    }
    

    One small ortimization on implementation is that:

    int[][] result = new int[res.size()][2];
            for (int i = 0; i < res.size(); i++) {
                result[i][0] = res.get(i)[0];
                result[i][1] = res.get(i)[1];
            }
    

    can be written as res.toArray(new int[size][2]);



沪ICP备19023445号-2号
友情链接