面试经典-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;
    }
}
相关推荐
liliangcsdn6 分钟前
多空价差收益序列汇总统计的分析和代码示例
人工智能·算法·机器学习
啥都想学点的研究生13 分钟前
一篇文章讲清楚:Adaboost算法与GBDT
人工智能·算法
旖旎夜光22 分钟前
LeetCode 525:连续数组(前缀和) —— 题解
数据结构·c++·算法·leetcode·前缀和
zander25839 分钟前
LeetCode 32. 最长有效括号
算法
lvwangshu1 小时前
AC 自动机
算法·字符串
shehuiyuelaiyuehao10 小时前
算法31,前缀和,可被k整除的子数组
数据结构·python·算法
203号居民12 小时前
LeetCode hot 100 — 141. 环形链表2
算法·leetcode·链表
玖玥拾12 小时前
LeetCode 202 快乐数
算法·leetcode
LuminousCPP12 小时前
数据结构-二叉树(六):BFS层序遍历与完全二叉树判断|复用链式队列 + (N_0=N_2+1) 性质证明
c语言·数据结构·笔记·算法·二叉树·宽度优先
ZhouDevin13 小时前
算法论文/数据集3——CLD(TMLR2025)压缩训练集,仅保留对验证集有益的样本
人工智能·深度学习·算法·计算机视觉