其他分享
首页 > 其他分享> > LeetCode 0056 Merge Intervals

LeetCode 0056 Merge Intervals

作者:互联网

原题传送门

1. 题目描述

2. Solution

1、思路分析
首先,对给定的intervals按start进行排序。然后将第一个区间加入result数组中,并按顺序依次考虑之后的每个区间:
case 1: 如果当前区间的start在result中最后一个区间的右端点之后,则不重合,可以将当前遍历区间加入到result中。
case 2: 否则重合,需要用当前区间的右端点,更新result中最后一个区间的右端点,将其置为二者中的较大值。
2、代码实现

package Q0099.Q0056MergeIntervals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;


public class Solution {

    /*
     The idea is to sort the intervals by their starting points.
     Then, we take the first interval and compare its end with the next intervals starts.
     As long as they overlap, we update the end to be the max end of the overlapping intervals.
     Once we find a non overlapping interval, we can add the previous "extended" interval and start over.

     Sorting takes O(n log(n)) and merging the intervals takes O(n). So, the resulting algorithm takes O(n log(n)).

      252 Meeting Rooms
      253 Meeting Rooms II
      435 Non-overlapping Intervals <- very similar, i did it with just 3 lines different
    */
    public int[][] merge(int[][] intervals) {
        if (intervals.length <= 1) return intervals;

        // Sort by ascending starting point
        Arrays.sort(intervals, Comparator.comparingInt(x -> x[0]));

        List<int[]> result = new ArrayList<>();
        int[] newInterval = intervals[0];
        result.add(newInterval);

        for (int[] interval : intervals) {
            if (interval[0] <= newInterval[1]) // Overlapping intervals, move the end if needed
                newInterval[1] = Math.max(newInterval[1], interval[1]);
            else {
                newInterval = interval;
                result.add(newInterval);
            }
        }

        return result.toArray(new int[result.size()][]);
    }
}

3、复杂度分析
时间复杂度: O(n logn)
空间复杂度: O(log n) 排序所需要的空间复杂度。

标签:Intervals,复杂度,interval,util,Merge,intervals,result,import,LeetCode
来源: https://www.cnblogs.com/junstat/p/16095099.html