面试经典-29- 插入区间

题目

给你一个 无重叠的 ,按照区间起始端点排序的区间列表。

在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

示例 1:

输入:intervals = \[1,3,6,9], newInterval = 2,5

输出:\[1,5,6,9]

java 复制代码
class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        int[][] temp = new int[intervals.length + 1][2];
        for (int i = 0; i < intervals.length; i++) {
            temp[i] = intervals[i];
        }
        temp[intervals.length] = newInterval;
        Arrays.sort(temp, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        // [[1,2],[3,5],[4,8],[6,7],[8,10],[12,16]]
        List<int[]> res = new ArrayList<>();
        int start = temp[0][0];
        int end = temp[0][1];
        for (int i = 1; i < temp.length; i++) {
            if (temp[i][0] > end) {
                res.add(new int[] { start, end });
                start = temp[i][0];
                end = temp[i][1];
            } else {
                end = Math.max(end,temp[i][1]);
            }
        }
        res.add(new int[] { start, end });
        int[][] result = new int[res.size()][2];
        for (int i = 0; i < res.size(); i++) {
            result[i] = res.get(i);
        }
        return result;
    }
}
相关推荐
小O的算法实验室8 小时前
IEEE TASE,基于MPC的多无人机协同搜索竞争群体优化方法
算法
Tbisnic9 小时前
BGE-M3 算法详解:从模型架构到三种检索方式的数学原理
算法·自然语言处理·大模型·bert·transformer·注意力机制
Brilliantwxx9 小时前
【算法从零到千】【55-58】哈希位图+常见数学运算 接口
算法
空堂与归10 小时前
用户分群找不到规律?用K-Means聚类算法自动发现数据模式
算法·机器学习·kmeans·聚类
动词ing10 小时前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习11 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
一只小小的芙厨11 小时前
基础数论总结
笔记·学习·算法
夜不会漫长12 小时前
C++入门(1)
开发语言·c++·算法
wen_zhufeng13 小时前
IndexTTS 2.5 技术报告
人工智能·算法·机器学习
大熊背14 小时前
树莓派相机自动白平衡详解(四)
算法·树莓派·白平衡·isppipeline