当前位置:网站首页>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,咱们宁可错杀一千,不可放过一个,都给他刷了_
边栏推荐
猜你喜欢
技术实现 | 图像检索及其在淘宝的应用
【论文笔记】Delving into the Estimation Shift of Batch Normalization in a Network
TiFlash 源码阅读(五) DeltaTree 存储引擎设计及实现分析 - Part 2
注意力机制
外包干了四年,秋招终于上岸了
TiCDC同步延迟问题处理
JSP基本语法
Cloud function to achieve automatic website check-in configuration details [Web function/Nodejs/cookie]
Anton Paar安东帕密度计比重计维修DMA35性能参数
binder通信实现
随机推荐
redis分布式锁的实现
async - await
LVGL's multi-language conversion tool -- a good assistant for font settings
It is found that several WRH tables are locked, what should I do?
三层交换机/路由器OSPF配置详解【华为eNSP实验】
Cloud function to achieve automatic website check-in configuration details [Web function/Nodejs/cookie]
ZbxTable 2.0 重磅发布!6大主要优化功能!
sql在字段重复时 对某个字段根据最新时间取数
加降息与BTC流动性事件策略研究
低代码应用开发的五大好处
[Punctuality Atomic STM32 Serial] Chapter 1 Learning Method of the Book Excerpted from [Punctuality Atomic] MiniPro STM32H750 Development Guide_V1.1
他97年的,我既然卷不过他...
Occupy, fill in later
.NET深入解析LINQ框架(五:IQueryable、IQueryProvider接口详解)
Thread类的基本使用。
从零开始的tensorflow小白使用指北
Explanation of spark operator
如何快速将Zabbix5.0升级至6.0?
BFM模型和Landmarks可视化
阿里云的数据库系统怎么升级更新的www.zgysffm.com怎么加快访问速度?