[Leetcode 57, Hard] Insert Interval
2015-07-20 23:01
267 查看
Problem:
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
as
Example 2:
Given
as
This is because the new interval
Analysis:
Solutions:
C++:
Python:
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].
Analysis:
Solutions:
C++:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { if(intervals.empty()) { intervals.push_back(newInterval); return intervals; } int start = newInterval.start; int end = newInterval.end; vector<Interval>::iterator start_it = intervals.begin(); for(; start_it != intervals.end(); ++start_it) { if(start_it->end >= newInterval.start) break; } if(start_it == intervals.end()) { intervals.push_back(newInterval); return intervals; } else { if(start_it->start > end) { intervals.insert(start_it, newInterval); return intervals; } else if(start_it->end >= end || start_it + 1 == intervals.end() || (start_it + 1)->start > end) { start_it->start = min(start, start_it->start); start_it->end = max(end, start_it->end); return intervals; } else start_it->start = min(start, start_it->start); } vector<Interval>::iterator end_it = start_it + 1; for(; end_it != intervals.end(); ++end_it) { if(end_it->end >= end) break; } if(end_it == intervals.end()) start_it->end = end; else { if(end_it->start <= end) { start_it->end = max(end, end_it->end); ++end_it; } else start_it->end = end; } intervals.erase(start_it + 1, end_it); return intervals; }Java:
Python:
相关文章推荐
- 无题
- IIS7.0 部署异常 【不能在此路径中使用此配置节。如果在父级别上锁定了该节,便会出现这种情况】解决方法
- Linux ssh
- 为了让你的网页能在更多的服务器上正常地显示,还是加上“SET NAMES UTF8”吧
- 任笑萱 2015/7/15 个人文档
- Springmvc+spring+maven+Mybatis整合
- oracle如何创建一个远程数据库上的某张表的同义词
- UVA-101 The Blocks Problem
- Java万年历,输入年月获取该年月日历表
- 从《大闹天宫》到《大圣归来》
- 架构师速成4.6-软技能和硬技能
- c编程:用户输入一个数值n,打印出出1到n之间的所有质数
- ARM机器码分析
- 架构师速成4.6-软技能和硬技能 分类: 架构师速成 2015-07-20 22:59 241人阅读 评论(0) 收藏
- 张珺 2015/07/16 个人文档
- c编程:用户输入一个数值n,打印出出1到n之间的所有质数
- 使用vSphere Client 上传文件到EXSI服务器
- openCV VS2012环境搭建
- 阻止手机浏览器双击放大的方法
- PHP连接数据库新方法phpPDO