面试经典-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;
    }
}
相关推荐
黎阳之光科技管控13 分钟前
纯视觉定位赋能海关口岸 无感通关提升国门安全与效率
算法·安全
じ☆冷颜〃23 分钟前
Picard–Lindelöf定理在CS中的应用:理论框架与算法基础
人工智能·经验分享·笔记·算法·机器学习
不知名的老吴28 分钟前
机器学习评价之基础指标
人工智能·算法·机器学习
Felven28 分钟前
D. Divisible Pairs
算法
源代码杀手29 分钟前
基于ROS2+Gazebo+RIVE的40项计算机视觉前沿机器人项目(含视觉算法原理与源码获取方式)
算法·计算机视觉·机器人
MrZhao40030 分钟前
大模型量化到底在做什么:从浮点数表示到 Qwen FP8 实践
算法
JieE21230 分钟前
LeetCode35. 搜索插入位置:二分查找的基础与细节
javascript·算法
8Qi837 分钟前
LeetCode 188 & 123:股票买卖问题(限制交易次数)—— 联合题解
算法·leetcode·职场和发展·动态规划
KaMeidebaby40 分钟前
卡梅德生物技术快报|细胞周期检测抗原流式分析:参数调试、软件拟合与问题排查
网络·人工智能·python·网络协议·tcp/ip·算法·机器学习
一只齐刘海的猫1 小时前
【Leetcode】三数之和
数据结构·算法·leetcode