当前位置:网站首页>数组表示若干个区间的集合,请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。【LeetCodeHot100】
数组表示若干个区间的集合,请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。【LeetCodeHot100】
2022-06-27 15:41:00 【小型骷髅】
力扣热题100之第56题:合并区间

先贴代码:
class Solution {
public int[][] merge(int[][] intervals) {
// 先对 intervals 数组进行排序
Arrays.sort(intervals, (v1, v2) -> v1[0] - v2[0]);
// 创建数组 list 存储合并后的区间
List<int[]> list = new ArrayList<int[]>();
for (int i = 0; i < intervals.length; i++) {
int L = intervals[i][0], R = intervals[i][1];
if (list.size() == 0 || list.get(list.size() - 1)[1] < L) {
list.add(new int[]{L, R});
} else {
list.get(list.size() - 1)[1] = Math.max(list.get(list.size() - 1)[1], R);
}
}
return list.toArray(new int[list.size()][]);
}
}解题思路:
本题中要求我们将所有可合并的区间全部合并,可合并的区间啥意思?就是这两个区间如果有交集,那么就属于可合并的区间。例如题目当中的例子:[ [1,3] , [2,6] , [8,10] , [15,18] ],在水平坐标线上表示如下:

可以看到,在以上四个区间中,只有红色区间和绿色区间有重叠部分,即有交集,那么说明红色区间 [1,3] 和绿色区间 [2,6] 是可合并的,合并后的区间为 [1,6] 。
了解完题意之后,这一题又该如何解答呢?
我们先来了解以一下两个区间可合并是有什么条件,因为上图可知,当两个区间有交集时,是可合并的,而且当两个区间,一个区间是另一个区间的子集时,这两个区间也是可合并的。所以当两个区间可合并时,条件就为前一个区间的最大值大于后一个区间的最小值,或者是一个区间包含另一个区间。由此我们可以判定,当两个区间的最小值按由小到大排列时,只判断最大值的大小即可。
由此可以获得解题思路,先将数组里的区间按照最小值由小到大排列,这样如果两个区间可合并,那么这两个区间一定是连续的!由于题目中的数组 intervals 是二维数组,所以在排序时需要用到 lambda 表达式:

也可以简写为:

这样就可以让 intervals 数组按照区间的最小值排列,然后我们再新建一个 list 来存储合并后的 区间。
边栏推荐
猜你喜欢

Li Chuang EDA learning notes 16: array copy and array distribution

2022年最新《谷粒学院开发教程》:8 - 前台登录功能

Eolink launched a support program for small and medium-sized enterprises and start-ups to empower enterprises!

Redis Series 2: data persistence improves availability

LeetCode每日一练(主要元素)

3.2 multiple condition judgment

List转Table

Leetcode daily practice (longest substring without repeated characters)

Domain name binding dynamic IP best practices

PSS:你距離NMS-free+提點只有兩個卷積層 | 2021論文
随机推荐
Design of digital video signal processor based on FPGA (with main code)
PSS: you are only two convolution layers away from the NMS free+ point | 2021 paper
Julia constructs diagonal matrix
What should the ultimate LAN transmission experience be like
PSS: vous n'êtes qu'à deux niveaux du NMS Free + Lifting point | 2021 Paper
机械硬盘和ssd固态硬盘的原理对比分析
Domain name binding dynamic IP best practices
OpenSSF安全计划:SBOM将驱动软件供应链安全
QT5.5.1桌面版安装配置过程中的疑难杂症处理(配置ARM编译套件)
LeetCode每日一练(两数之和)
Leetcode daily practice (longest substring without repeated characters)
锚文本大量丢失的问题
List转Table
Pisa-Proxy 之 SQL 解析实践
16 -- remove invalid parentheses
守护雪山之王:这些AI研究者找到了技术的新「用武之地」
ICML 2022 ぷ the latest fedformer of the Dharma Institute of Afghanistan ⻓ surpasses SOTA in the whole process of time series prediction
What are the password requirements for waiting insurance 2.0? What are the legal bases?
Cesium uses mediastreamrecorder or mediarecorder to record screen and download video, as well as turn on camera recording. [transfer]
2022年最新《谷粒学院开发教程》:8 - 前台登录功能