LeetCode134|插入区间

1,问题简述

    给出一个无重叠的 ,按照区间起始端点排序的区间列表。在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

2,示例

示例 1:


输入:intervals = [[1,3],[6,9]], newInterval = [2,5]
输出:[[1,5],[6,9]]
示例 2:


输入:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
输出:[[1,2],[3,10],[12,16]]
解释:这是因为新的区间 [4,8] 与 [3,5],[6,7],[8,10] 重叠。
 


注意:输入类型已在 2019 年 4 月 15 日更改。请重置为默认代码定义以获取新的方法签名。


 

3,题解思路

     其实这道题和前面的合并区间那道题的整个题解思路是一样的,将新数组元素装入到集合里面,然后将集合元素排序一下,然后进行逻辑判断,这里使用了集合作为一个临时存储空间,比较相邻区间的内容,如前一个区间右端点的值和下一个区间左端点的值做比较,符合合并的时候进行合并之后放入结果集,不符合合并的也放入结果集中,当所有的区间都处理完成之后,符合合并的数据就处理完成了,这也是本题的主要思路

4,题解程序



import java.util.*;


public class InsertTest {
    public static void main(String[] args) {
        int[][] intervals = {
                {1, 3},
                {6, 9}
        };


        int[] newInterval = {2, 5};




        int[][] insert = insert(intervals, newInterval);
        for (int[] arr : insert) {
            System.out.println(arr[0] + "    " + arr[1]);
        }
    }


    public static int[][] insert(int[][] intervals, int[] newInterval) {
        if ((intervals == null) && newInterval == null) {
            return new int[][]{newInterval};
        }


        List<int[]> list = new ArrayList<>();
        Collections.addAll(list, intervals);
        list.add(newInterval);
        int[][] tempArray = list.toArray(new int[0][]);
        List<int[]> result = new ArrayList<>();
        Arrays.sort(tempArray, Comparator.comparingInt(x -> x[0]));
        List<int[]> tempList = new ArrayList<>();
        Collections.addAll(tempList, tempArray);
        int[] temp = tempList.get(0);
        for (int i = 1; i < tempList.size(); i++) {
            if (tempList.get(i)[0] <= temp[1]) {
                temp = new int[]{temp[0], Math.max(temp[1], tempList.get(i)[1])};
            } else {
                result.add(temp);
                temp = tempList.get(i);
            }
        }
        result.add(temp);
        int[][] array = result.toArray(new int[0][]);
        return array;
    }
}


5,题解程序图片版

6,总结一下

    其实对于每个读者而言,都希望以及渴望在自己读到的每一天文章时都可以及时获取到自己需要的内容,比如说程序题吧,如果你不讲解一下大致的实现思路,压根就没有人去理会你这道题的整体实现,除非到了迫不得已的地步,但是这种情况非常少,因为看是为了长一点知识,扩充一点自己的内容,但是, 看了你的文章,自己还是不懂,是分享者没有写好他的程序还是自己理解不到位,都有责任吧,总之分享者如果想留住读者对文章阅读或者思考的时间,真的需要为自己的读者去考虑一下,不然别人关注你干嘛呢,现在有的文章满屏广告,各有各的道理吧,总之不能评价这些内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值