当前位置:网站首页>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,咱们宁可错杀一千,不可放过一个,都给他刷了_
边栏推荐
猜你喜欢
![[STM32] STM32F103 series name and package, memory](/img/01/073f970c8c05ad24f976b26790ba61.png)
[STM32] STM32F103 series name and package, memory

如何快速将Zabbix5.0升级至6.0?

蘑菇书EasyRL学习笔记
![Detailed explanation of switch link aggregation [Huawei eNSP]](/img/c2/f9797fe8b17a418466b60cc3dc50a1.png)
Detailed explanation of switch link aggregation [Huawei eNSP]
![[NOI Simulation Competition] Paper Tiger Game (Game Theory SG Function, Long Chain Division)](/img/b7/21f82453576b81e64dafbc3975125f.png)
[NOI Simulation Competition] Paper Tiger Game (Game Theory SG Function, Long Chain Division)

ZbxTable 2.0 重磅发布!6大主要优化功能!

NAT/NAPT地址转换(内外网通信)技术详解【华为eNSP】

cannot import name ‘import_string‘ from ‘werkzeug‘【bug解决】

智汇华云 | 华云软件定义网络 DCI介绍
![[Computer recording screen] How to use bandicam to record the game setting graphic tutorial](/img/a7/0ac5e2028c5f1b013da56b795143e7.jpg)
[Computer recording screen] How to use bandicam to record the game setting graphic tutorial
随机推荐
阿里云的数据库系统怎么升级更新的www.zgysffm.com怎么加快访问速度?
王爽汇编语言第四章:第一个程序
大佬们,mysql里text类型的字段,FlinkCDC需要特殊处理吗 就像处理bigint uns
sql在字段重复时 对某个字段根据最新时间取数
大家好,请教一个问题啊,我们通过flinkcdc把Oracle数据同步到doris,目前的问题是,只
【无标题】
将jpg图片转换成yuv420(NV12)数据文件
cannot import name 'import_string' from 'werkzeug' [bug solution]
Layer 3 Switch/Router OSPF Configuration Details [Huawei eNSP Experiment]
Detailed explanation of NAT/NAPT address translation (internal and external network communication) technology [Huawei eNSP]
张朝阳对话俞敏洪:谈宇宙、谈焦虑、谈创业、谈退休、谈人生
低代码应用开发的五大好处
关于Oracle RAC 11g重建磁盘组的问题
记录十条工作中便利的API小技巧
async - await
The separation configuration Libpq is supported, speaking, reading and writing
ISO14443A读卡流程(作为示例参考)
C Language Lectures from Scratch Part 6: Structure
云函数实现网站自动化签到配置详解【Web函数/Nodejs/cookie】
OAK-FFC-4P全网首次测试