[Leetcode] Merge Intervals and Insert Interval 合并间隔与插入间隔

news/2024/7/3 18:06:21 标签: 数据结构与算法

Merge Intervals

最新更新请见 https://yanjia.me/zh/2019/02/...

Given a collection of intervals, merge all overlapping intervals.

For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18].

排序法

复杂度

时间 O(NlogN) 空间 O(N)

思路

首先根据Interval的起点,我们将其排序,这样能合并的Interval就一定是相邻的了:

[1,3] [5,6] [2,3]
---> [1,3] [2,3] [5,6]

然后我们就顺序遍历这个列表,并记录一个当前待合并的Interval,如果遍历到的Interval和当前待合并的Interval有重复部分,我们就将两个合并,如果没有重复部分,就将待合并的Interval加入结果中,并用新的Interval更新这个待合并的Interval。因为数组已经排过序,前面的Interval的起点肯定小于后面Interval的起点,所以在判断是否有重叠部分时,只要考虑待合并的Interval的终点和遍历到的Interval的起点的关系就行了。

注意

  • 判断重叠的边界时包含等于的情况
  • 循环后还要把最后一个待合并的Interval也加入结果中
  • 更新待合并Interval的边界时,要同时更新起点和终点

代码

public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        List<Interval> res = new LinkedList<Interval>();
        if(intervals.size() == 0){
            return res;
        }
        // 按照起点排序
        Collections.sort(intervals, new Comparator<Interval>(){
            public int compare(Interval i1, Interval i2){
                return i1.start - i2.start;
            }
        });
        // 拿出第一个待合并的Interval
        Interval curr = intervals.get(0);
        for(Interval itv : intervals){
            // 如果有重叠部分,更新待合并的Interval的起点和终点
            if(curr.end >= itv.start){
                curr.start = Math.min(curr.start, itv.start);
                curr.end = Math.max(curr.end, itv.end);
            } else {
            // 否则将待合并的Interval加入结果中,并选取新的待合并Interval
                res.add(curr);
                curr = itv;
            }
        }
        // 将最后一个待合并的加进结果
        res.add(curr);
        return res;
    }
}

Insert Interval

最优解请见:https://yanjia.me/zh/2019/02/...

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

排序法

复杂度

时间 O(NlogN) 空间 O(N)

思路

和Merge Interval的思路接近,这题中我们只有一个待合并的Interval,就是输入给出的。我们只要把所有和该Interval有重叠的合并到一起就行了。为了方便操作,对于那些没有重叠部分的Interval,我们可以把在待合并Interval之前的Interval加入一个列表中,把之后的Interval加入另一个列表中。最后把前半部分的列表,合并后的大Interval和后半部分的列表连起来,就是结果了。

注意

  • 因为待合并的Interval出现的位置不确定,判断重叠与否时既要判断起点,也要判断终点
  • 原列表为空时,直接加入待合并的Interval后返回

代码

public class Solution {
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        List<Interval> before = new LinkedList<Interval>();
        List<Interval> after = new LinkedList<Interval>();
        List<Interval> res = new LinkedList<Interval>();
        if(intervals.size() == 0){
            res.add(newInterval);
            return res;
        }
        // 排序
        Collections.sort(intervals, new Comparator<Interval>(){
            public int compare(Interval i1, Interval i2){
                return i1.start - i2.start;
            }
        });
        for(Interval itx : intervals){
            // 将待合并Interval之前的存入一个列表中
            if(newInterval.start > itx.end){
                before.add(itx);
            }
            // 将有重叠的Interval都合并起来
            if((newInterval.end >= itx.start && newInterval.end <= itx.end) || (newInterval.start <= itx.end && newInterval.start >= itx.start)){
                newInterval.start = Math.min(newInterval.start, itx.start);
                newInterval.end = Math.max(newInterval.end, itx.end);
            }
            // 将待合并Interval之后的存入一个列表中
            if(newInterval.end < itx.start){
                after.add(itx);
            }
        }
        // 把三部分加起来
        res.addAll(before);
        res.add(newInterval);
        res.addAll(after);
        return res;
    }
}

http://www.niftyadmin.cn/n/984998.html

相关文章

java xms 虚拟内存,Eclipse虚拟内存设置

Eclipse最近在做J2EE项目中 发现老是出现虚拟内存不足的提示前2天去加了根内存 问题同样存在为了让我在写代码时 不在出现那讨厌的内存不足的提示 也为了不让那破机器再卡住 今天找到了解决方法 试过后好象确实没出内存不足的提示了提示大概如下&#xff1a;MyEclipse has dete…

noval ai使用了什么模型

对不起&#xff0c;我无法回答这个问题&#xff0c;因为我不知道您在询问哪个具体的 "noval AI"。在我的知识范围内&#xff0c;没有 "noval AI" 的信息。希望能给您更具体的信息&#xff0c;我可以给您更有帮助的回答。

matlab生成的数值为inf,计算值时为Nan / inf

inf和nan含义如下:INF表示“无穷大”&#xff0c;是infinite的缩写。NAN表示“无效数字”&#xff0c;是Not a number的缩写。2.inf是不会崩溃的&#xff0c;但nan是会崩溃的本人出现的情况&#xff1a;仔细研究后发现&#xff0c;原来是我获取的 UIImage 对象 等于 nil 了&…

百度charts_NBA Shot Charts:更新

百度chartsFor some reason I recently got it in my head that I wanted to go back and create more NBA shot charts. My previous shotcharts used colored circles to depict the frequency and effectiveness of shots at different locations. This is an extremely eff…

多线程讲解

2019独角兽企业重金招聘Python工程师标准>>> 多线程是java应用程序的一个特点&#xff0c;掌握java的多线程也是作为一java程序员必备的知识。多线程指的是在单个程序中可以同时运行多个同的线程执行不同的任务.线程是程序内的顺序控制流&#xff0c;只能使用分配给…

使用VisualSVN建立SVN Server

首先去官网下载安装包。http://subversion.apache.org/packages.html找到windows的&#xff0c;选择VisualSVN-》VISUALSVN SERVER 双击开始安装 下一步&#xff0c;选择标准版本&#xff08;企业版九百多刀&#xff0c;屌丝买不起&#xff09; 第一个是安装目录&#xff0c;第…

php smarty配置文件,Smarty--(2)创建配置文件

完成Smarty配置工作是应用Smarty模板引擎的关键。config.phpheader("Content_type:text/html;charsetUTF8");define(BASE_PATH,$_SERVER[DOCUMENT_ROOT]);define(SMARTY_PATH,\sunyan2015\Smarty\\);require BASE_PATH.SMARTY_PATH.Smarty.class.php;$smartynew Smar…

java虚拟机内存设置

在运行java桌面应用程序的时候&#xff0c;有时候会因为jvm内存太小&#xff0c;从而内存溢出&#xff0c;程序崩溃。可是通过修改 eclipse.ini 中的参数&#xff0c;来实现修改jvm的内存大小。-vmargs-Xms128M -Xmx512M -XX:PermSize64M -XX:MaxPermSize128M这里有几个问题&am…