ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode 0056 Merge Intervals

2022-04-03 09:02:52  阅读:204  来源: 互联网

标签:Intervals 复杂度 interval util Merge intervals result import LeetCode


原题传送门

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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有