面试经典-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;
    }
}
相关推荐
gihigo19987 小时前
matlab 基于瑞利衰落信道的误码率分析
算法
foxsen_xia7 小时前
go(基础06)——结构体取代类
开发语言·算法·golang
foxsen_xia7 小时前
go(基础08)——多态
算法·golang
leoufung7 小时前
用三色 DFS 拿下 Course Schedule(LeetCode 207)
算法·leetcode·深度优先
im_AMBER8 小时前
算法笔记 18 二分查找
数据结构·笔记·学习·算法
C雨后彩虹9 小时前
机器人活动区域
java·数据结构·算法·华为·面试
MarkHD9 小时前
车辆TBOX科普 第53次 三位一体智能车辆监控:电子围栏算法、驾驶行为分析与故障诊断逻辑深度解析
算法
苏小瀚9 小时前
[算法]---路径问题
数据结构·算法·leetcode
月明长歌10 小时前
【码道初阶】一道经典简单题:多数元素(LeetCode 169)|Boyer-Moore 投票算法详解
算法·leetcode·职场和发展
wadesir10 小时前
C语言模块化设计入门指南(从零开始构建清晰可维护的C程序)
c语言·开发语言·算法