当前位置:网站首页>leetcode经典例题——56.合并区间
leetcode经典例题——56.合并区间
2022-08-04 09:03:00 【你食不食油饼】
题目描述:

思路:咱们看到合并区间就先不管他有几个区间的集合,假设我们现在有两个区间的集合:
如果两个区间[1,3]、[2,6],因为3>2,3<6所以合并区间[1,6];
如果两个区间[1,7]、[2,6],因为7>2,7>6所以合并区间[1,7];
如果两个区间[1,3]、[4,6],因为3<4所以不用合并,还是原来两个区间[1,3]、[4,6];
当我们进行合并的时候我们只需要考虑这三种情况,所以现在的问题就是如何把若干个区间转化为上面这种比较的情况;
我们来看看带码就能理解:
public int[][] merge(int[][] intervals) {
//先给数组排序
Arrays.sort(intervals,(a,b)->{return a[0]-b[0];});
//用来装合并好的区间
int[][] res = new int[intervals.length][2];
int index = 0;
for (int i = 0,j ; i < intervals.length;) {
j = i+1;
while (j<intervals.length && intervals[i][1] >= intervals[j][0]){
if(intervals[i][1] <= intervals[j][1])
intervals[i][1] = intervals[j][1];
else intervals[j][1] = intervals[i][1];
j++;
}
res[index][0] = intervals[i][0];
res[index][1] = intervals[j-1][1];
i = j;
index++;
}
return Arrays.copyOf(res, index);
}时间复杂度:O(n),虽然是双重循环,但只要遍历完数组就结束了
空间复杂度:O(n)
总结:这道题是一道比较偏逻辑的题目,没有用到什么算法,但作为leetcode热题100,咱们宁可错杀一千,不可放过一个,都给他刷了_
边栏推荐
- B站回应HR称“核心用户都是Loser”、求职者是“白嫖党”:已被劝退
- Yolov5 replaces the backbone network of "Megvii Lightweight Convolutional Neural Network ShuffleNetv2"
- Fiddler(一)安装
- The separation configuration Libpq is supported, speaking, reading and writing
- Explanation of spark operator
- 大家好,请教一个问题啊,我们通过flinkcdc把Oracle数据同步到doris,目前的问题是,只
- BFM模型和Landmarks可视化
- 94后字节P7晒出工资单:狠补了这个,真不错...
- async - await
- VRRP + MSTP configuration, huawei eNSP experiment 】 【
猜你喜欢

Interview at 14:00 in the afternoon, I came out at 14:08 with my head down, asking too much...
![Could you please talk about how the website is accessed?[Interview questions in the web field]](/img/06/5ecc617edc4131c31f71d5e019a64c.png)
Could you please talk about how the website is accessed?[Interview questions in the web field]

下午14:00面试,14:08低着头出来了 ,问的实在是太...

PD 源码分析- Checker: region 健康卫士

TiCDC同步延迟问题处理
![[Punctuality Atom STM32 Serial] Chapter 4 STM32 First Experience Excerpted from [Punctual Atom] MiniPro STM32H750 Development Guide_V1.1](/img/99/928e86f8a61a905a899dd5d3880def.png)
[Punctuality Atom STM32 Serial] Chapter 4 STM32 First Experience Excerpted from [Punctual Atom] MiniPro STM32H750 Development Guide_V1.1

菲沃泰科创板上市:市值123亿 宗坚赵静艳夫妇身价76亿

spark算子讲解

云函数实现网站自动化签到配置详解【Web函数/Nodejs/cookie】

BFM模型和Landmarks可视化
随机推荐
layout manager
微信消息从发送到接收,经历了什么?如何防止丢包
我和 TiDB 的故事 | TiDB 对我不离不弃,我亦如此
今年37了,被大厂抢着要...
telnet远程登录aaa模式详解【华为eNSP】
Post-94 Byte P7 posted the salary slip: It's really good to make up for this...
TiFlash 源码阅读(五) DeltaTree 存储引擎设计及实现分析 - Part 2
2022年制冷与空调设备运行操作特种作业证考试题库及模拟考试
Thread类的基本使用。
2022年化工自动化控制仪表考试模拟100题及模拟考试
外包干了四年,秋招终于上岸了
【正点原子STM32连载】第四章 STM32初体验 摘自【正点原子】MiniPro STM32H750 开发指南_V1.1
oracle sql multi-table query
发现WRH几个表被锁了,怎么办?
递归思想
MATLAB绘图总结
PD 源码分析- Checker: region 健康卫士
Shared_preload_libraries cause many syntaxes not supported
【论文笔记】Dynamic Convolution: Attention over Convolution Kernels
一道[CSCCTF 2019 Qual]FlaskLight的详解再遇SSTI