当前位置:网站首页>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,咱们宁可错杀一千,不可放过一个,都给他刷了_
边栏推荐
- JSP基本语法
- Shared_preload_libraries cause many syntaxes not supported
- 我和 TiDB 的故事 | 缘份在,那就终是能相遇的
- TiCDC同步延迟问题处理
- cannot import name 'import_string' from 'werkzeug' [bug solution]
- 字符串与正则表达式(C#)
- NAT/NAPT地址转换(内外网通信)技术详解【华为eNSP】
- 软件工程国考总结——判断题
- Recommend several methods that can directly translate PDF English documents
- redis分布式锁的实现
猜你喜欢
Apache Druid 实时分析数据库入门介绍
How many assertion methods are commonly used in JMeter?
基于cRIO-904X搭建Simulink与Labview环境
【论文笔记】Understanding Long Programming Languages with Structure-Aware Sparse Attention
思想茶叶蛋 (Jul 31,2022)| 元宇宙(Metaverse)下了一枚什么样的蛋
VRRP+MSTP配置详解【华为eNSP实验】
ISO14443A读卡流程(作为示例参考)
layout manager
No module named 'flask_misaka' has been resolved [BUG solution]
telnet远程登录aaa模式详解【华为eNSP】
随机推荐
[Punctuality Atomic STM32 Serial] Chapter 1 Learning Method of the Book Excerpted from [Punctuality Atomic] MiniPro STM32H750 Development Guide_V1.1
csdn图片去水印 | 其他方法无效时的解决方案
速速脱单诀窍
将jpg图片转换成yuv420(NV12)数据文件
It is found that several WRH tables are locked, what should I do?
layout manager
Recommend several methods that can directly translate PDF English documents
How many assertion methods are commonly used in JMeter?
How to import data from PG to kingbaseES
TCP的四次挥手
VRRP+MSTP配置详解【华为eNSP实验】
用OpenGL绘制winXP版扫雷的笑脸表情
获取cpu的核数
学会 Arthas,让你 3 年经验掌握 5 年功力
【STM32】STM32F103系列名称与封装、内存
recursive thinking
Cloud function to achieve automatic website check-in configuration details [Web function/Nodejs/cookie]
[STM32] STM32F103 series name and package, memory
redis分布式锁的实现
线程的状态