Insert Interval
来源:互联网 发布:js鼠标事件怎么用 编辑:程序博客网 时间:2024/05/17 13:43
一. Insert Interval
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].
Difficulty:Hard
TIME:TIMEOUT
解法
这道题的题意很简单,但是也不是那么容易就能写出正确而且简洁的代码。
其实这道题大约可以分为三种情况,第一种就是overlap之前,第二种就是overlap之中,第三种就是overlap之后。
一开始我想的是通过一个for循环来判断各种情况,不过后面发现那样写太过复杂。因此改成了三个循环的模式,分别对应三种情况,这样判断的条件就会少很多。
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { vector<Interval> result; int i = 0; /*第一次循环,跳过overlap之前的数据*/ while(i < intervals.size() && newInterval.start > intervals[i].end) { result.push_back(intervals[i]); i++; } result.push_back(newInterval); /*第二次循环,overlap的处理*/ while(i < intervals.size() && newInterval.end >= intervals[i].start) { result.back().start = min(intervals[i].start, result.back().start); result.back().end = max(intervals[i].end, result.back().end); i++; } /*第三次循环,跳过overlap之后的数据*/ while(i < intervals.size()) { result.push_back(intervals[i]); i++; } return result;}
代码的时间复杂度为
0 0
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Unit13 作业练习
- 1.scala之HelloWorld
- QQ Aizu
- jeesite开发平台业务表要求
- unit9 ssh
- Insert Interval
- Spring学习-21:Spring的AOP:基于AspectJ的注解开发
- android studio的debug和release模式下使用不同的Http前缀进行测试与正式环境的自动切换
- Linux C TCP Socket实现客户与服务器简单通信
- JavaWeb框架梳理
- ZOJ2966
- OSGBullet碰撞检测小程序
- Android Intent
- POJ 1088 滑雪