面试经典-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;
    }
}
相关推荐
网域小星球2 分钟前
C 语言从 0 入门(二十一)|typedef 类型重定义:简化复杂类型,代码更清爽
c语言·算法·类型重定义·结构体简化·函数指针简化
XWalnut7 分钟前
LeetCode刷题 day10
数据结构·算法·leetcode
programhelp_44 分钟前
Amazon OA 2026 高频题型拆解 + 速通攻略
数据结构·算法
moonsea02031 小时前
2026.4.14
数据结构·算法·图论
x_xbx1 小时前
LeetCode:42. 接雨水
算法·leetcode·职场和发展
lixinnnn.1 小时前
01BFS:小明的游戏
算法
falldeep1 小时前
Claude Code源码分析
人工智能·算法·机器学习·强化学习
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2026.04.14 题目:2463.最小移动距离
笔记·算法·leetcode
feng_you_ying_li1 小时前
C++11可变模板参数,包扩展,emplace系列和push系列的区别
前端·c++·算法
tankeven1 小时前
HJ177 可匹配子段计数
c++·算法