博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode] insert interval 插入区间
阅读量:4512 次
发布时间:2019-06-08

本文共 1716 字,大约阅读时间需要 5 分钟。

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1: 

Given intervals[1,3],[6,9], insert and merge[2,5]in as[1,5],[6,9].

Example 2: 

Given[1,2],[3,5],[6,7],[8,10],[12,16], insert and merge[4,9]in as[1,2],[3,10],[12,16].

This is because the new interval[4,9]overlaps with[3,5],[6,7],[8,10].

 题意:给定一个区间,将其插入以排序的区间中。

思路:这题是的扩展。就是用要插入的区间和区间集合中对比,有三种情况:

一)待插入区间的右端点小于区间集合中当前的左端点,即,没有交叉,则将区间压入栈中,然后将区间集合中的后续的区间一次压入结果中;

二)若待插入区间的左端点大于区间集合中当前的右端点,即没有交叉,将当前的区间压入结果中;

三)若,待插入的左端点大于当前的左端点,右端点小于有(或者大于)当前的右端点,或,待插入的左端点的小于当前的左端点,右端点大于当前的左端点,即只要两个区间有交叉;这种情况,我们只要取左端点中的较小值,右端点中的较大值,形成新的区间和区间集合中的后续区间比较。

代码如下:

1 /** 2  * Definition for an interval. 3  * struct Interval { 4  *     int start; 5  *     int end; 6  *     Interval() : start(0), end(0) {} 7  *     Interval(int s, int e) : start(s), end(e) {} 8  * }; 9  */10 class Solution {11 public:12     vector
insert(vector
&intervals, Interval newInterval) 13 {14 vector
res;15 if(intervals.empty())16 {17 res.push_back(newInterval);18 return res;19 }20 21 for(int i=0;i
intervals[i].end)34 res.push_back(intervals[i]);35 else36 {37 newInterval.start=min(newInterval.start,intervals[i].start);38 newInterval.end=max(newInterval.end,intervals[i].end);39 }40 }41 res.push_back(newInterval);42 return res; 43 }44 };

 

转载于:https://www.cnblogs.com/love-yh/p/7196256.html

你可能感兴趣的文章
硬链接和软链接
查看>>
Python——thread
查看>>
Python网络编程(4)——异步编程select & epoll
查看>>
中国智能车未来挑战赛——复杂交通环境认知基础能力离线测试
查看>>
app之间的跳转
查看>>
javascript event loop
查看>>
LIS
查看>>
FastIO
查看>>
字符串循环右移-c语言
查看>>
解决从pl/sql查看oracle的number(19)类型数据为科学计数法的有关问题
查看>>
古训《增广贤文》
查看>>
职场的真相——七句话
查看>>
xcode命令行编译时:codesign命令,抛出“User interaction is not allowed.”异常 的处理...
查看>>
[转载]开机出现A disk read error occurred错误
查看>>
STM32 C++编程 002 GPIO类
查看>>
无线冲方案 MCU vs SoC
查看>>
进程装载过程分析(execve系统调用分析)
查看>>
在windows 7中禁用media sense
查看>>
ELK-Elasticsearch安装
查看>>
anglar JS使用两层ng-repeat嵌套使用,分辨$index
查看>>