面试经典-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;
    }
}
相关推荐
猎板PCB厚铜专家大族24 分钟前
2025有铜半孔工艺参数设计规范
网络·算法·设计规范
白熊18844 分钟前
【图像大模型】AnimateDiff:基于扩散模型的视频生成技术解析与实践指南
人工智能·算法·音视频
虾球xz2 小时前
游戏引擎学习第309天:用于重叠检测的网格划分
c++·学习·算法·游戏引擎
买了一束花3 小时前
预分配矩阵内存提升文件数据读取速度
java·人工智能·算法·matlab
不忘不弃4 小时前
由浮点数的位级表示判断大小关系
c语言·算法
wuqingshun3141594 小时前
蓝桥杯 3. 涂色
c++·算法·职场和发展·蓝桥杯·深度优先
白杆杆红伞伞4 小时前
05_核支持向量机
算法·机器学习·支持向量机
wuqingshun3141594 小时前
蓝桥杯 10. 安全序列
c++·算法·职场和发展·蓝桥杯·深度优先
和八哥的环球探险4 小时前
数据结构与算法分析实验14 实现基本排序算法
数据结构·算法·排序算法