博客
关于我
【leetcode】合并区间
阅读量:541 次
发布时间:2019-03-09

本文共 1273 字,大约阅读时间需要 4 分钟。

要解决给定一组区间并合并所有重叠区间的问题,可以按照以下步骤进行:

步骤 1:排序区间

首先,将所有区间按照起点进行升序排序。这样可以方便地比较相邻区间,判断是否存在重叠。

步骤 2:初始化结果列表

创建一个空的结果列表,用于存储最终的合并区间。

步骤 3:处理空输入

如果输入的区间集合为空,直接返回空数组。

步骤 4:遍历区间

从排序后的第一个区间开始遍历,逐个检查相邻区间是否存在重叠。

步骤 5:比较区间

对于当前区间和下一个区间,检查当前区间的结束点是否大于等于下一个区间的起点。如果是,说明存在重叠,合并两个区间,更新当前区间的结束点。如果不是,添加下一个区间到结果列表,并更新当前区间。

步骤 6:返回结果

将结果列表转换为数组并返回。

代码实现

以下是Java实现的代码:

import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Solution {    public int[][] merge(int[][] intervals) {        List
res = new ArrayList<>(); if (intervals.length == 0) { return new int[0][]; } Arrays.sort(intervals, (a, b) -> a[0] - b[0]); int[] current = intervals[0]; res.add(current); for (int i = 1; i < intervals.length; i++) { int[] next = intervals[i]; if (next[0] <= current[1]) { current[1] = Math.max(current[1], next[1]); } else { res.add(next); current = next; } } return res.toArray(new int[][]); }}

解释

  • 排序:使用Arrays.sort对区间数组进行排序,确保区间按起点升序排列。
  • 初始化:创建结果列表res,并处理空输入情况。
  • 遍历:从第二个区间开始遍历,检查每个区间与前一个区间是否存在重叠。
  • 合并:如果存在重叠,合并两个区间,更新当前区间的结束点;否则,将区间添加到结果列表。
  • 返回:将结果列表转换为数组并返回。
  • 这个方法确保了所有重叠区间被正确合并,时间复杂度为O(n log n),主要来自于排序操作。

    转载地址:http://rxhiz.baihongyu.com/

    你可能感兴趣的文章
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
    查看>>
    SQL-CLR 类型映射 (LINQ to SQL)
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>
    org.tinygroup.serviceprocessor-服务处理器
    查看>>
    org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
    查看>>