面试经典-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;
    }
}
相关推荐
To_OC23 分钟前
LC 15 三数之和:双指针不难,难的是把去重做对
javascript·算法·leetcode
renhongxia13 小时前
世界模型,是“空中楼阁”还是AGI的“最后一块拼图”?
运维·服务器·数据库·人工智能·算法·agi
zephyr055 小时前
动态规划-最长上升子序列问题
算法·动态规划
闪电悠米5 小时前
力扣hot100-56.合并区间-排序详解
数据结构·算法·leetcode·贪心算法·排序算法
卡提西亚6 小时前
leetcode-1438. 绝对差不超过限制的最长连续子数组
算法·leetcode·职场和发展
Java面试题总结7 小时前
LeetCode 93.复原IP地址
算法·leetcode·职场和发展·.net
从零开始的代码生活_7 小时前
C++ 多态详解:虚函数、动态绑定、抽象类与虚表原理
开发语言·c++·后端·学习·算法
Tisfy8 小时前
LeetCode 3867.数对的最大公约数之和:按题目说的做(gcd)
算法·leetcode·题解·模拟·最大公约数·gcd
泷寂8 小时前
最小生成树 (MST基础)
算法
Daniel_1238 小时前
数组——总结篇
算法