LeetCode:合并区间

java 复制代码
class Solution {
    public int[][] merge(int[][] intervals) {
        if(intervals == null || intervals.length == 0){
            return new int[0][2];
        }

        //先按照左边界进行排序
        Arrays.sort(intervals, (a,b) -> Integer.compare(a[0],b[0]));
        //不知道最终有几个,使用动态扩容
        List<int[]> merged = new ArrayList<>();

        int[] currentInterval = intervals[0];
        merged.add(currentInterval);

        for(int[] nextInterval : intervals){
            //第一轮循环会重复测试一下第一个数组
            int currentEnd = currentInterval[1];
            int nextStart = nextInterval[0];
            int nextEnd = nextInterval[1];
            //判断是否重叠
            if(nextStart <= currentEnd){
                currentInterval[1] = Math.max(currentEnd,nextEnd);
            }else{
                currentInterval = nextInterval;
                merged.add(currentInterval);
            }
        }
        return merged.toArray(new int[merged.size()][]);
    }
}

动态扩容:

ArrayList先申请一个默认为0的原生数组elementData,存元素时申请一个默认容量为10的新数组,新数组满的时候,申请新数组长度为原来的1.5倍,将原来数组的东西通过System.arraycopy方法复制到新数组中,将旧数组交给垃圾回收器(GC)。

引用传递:

多个变量名共同管理内存里的同一个对象实体,最终看到的结果也同步改变。

相关推荐
凌冰_8 小时前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
Pniubi9 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
戴·菲瑜9 小时前
为什么PPO难以做出顶级棋类引擎
算法·博弈论·rl·ppo
在所不辞兄11 小时前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
文丑颜不良啊15 小时前
LeetCode3401~3420题目解析
java·leetcode
AvocadoZeroOneOI16 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
文丑颜不良啊16 小时前
LeetCode3421~3440题目解析
java·leetcode
cjz389918 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
橘子1321 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘1 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法