Insert Interval
2015-07-09 22:40
344 查看
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].
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> res = new ArrayList<Interval>();
if (intervals.size() == 0) {
intervals.add(newInterval);
return intervals;
}
int i = 0;
while (i < intervals.size() && intervals.get(i).end < newInterval.start) {
res.add(intervals.get(i));
i++;
}
if (i < intervals.size()) {
newInterval.start = Math.min(intervals.get(i).start, newInterval.start);
}
res.add(newInterval);
while (i < intervals.size() && intervals.get(i).start <= newInterval.end) {
newInterval.end = Math.max(newInterval.end, intervals.get(i).end);
i++;
}
while(i < intervals.size()) {
res.add(intervals.get(i));
i++;
}
return res;
}
}
相关文章推荐
- PayPal高级工程总监:读完这100篇论文 就能成大数据高手
- 导入外来项目工程时出错。
- Reporting Service表达式与报表函数
- github上传项目
- 浅谈深拷贝和浅拷贝
- Reporting Service表达式与报表函数
- js模态窗口
- Median of Two Sorted Arrays
- 设计模式--工厂模式(工厂方法、抽象工厂)
- Android开发————启动android virtual devices
- 苹果开发 笔记(46)圆角
- 代理模式 Proxy
- Ubuntu下Sublime Text 3解决无法输入中文的方法
- Fragment的一些基础
- OSGEarth绘制Geometry:绘多边形(三)
- 1. JavaScript 基础
- 使用Oracle sqlldr 快速批量导入文本文件
- EHCache入门系列(二)–在工程中单独使用
- 深入理解JAVA的多态性[转]
- 黑马程序员——高新技术---Java基础语法-循环结构和跳转语句