## [LeetCode]Insert Interval

2018年05月13日 ⁄ 综合 ⁄ 共 1512字 ⁄ 字号 评论关闭

Given a non-overlapping interval list which is sorted by start point.

Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).

Example

Insert [2, 5] into [[1,2], [5,9]], we get [[1,9]].

Insert [3, 4] into [[1,2], [5,9]], we get [[1,2],
[3,4], [5,9]]
.

a. 在迭代的时候，情况2 会将比较段设置为null，所有如果比较段为null，直接执行情况1

b. 在循环结束后，判定，如果比较段不为null，则最后插入比较段（之前都为插入）

```/**
* Definition of Interval:
* public classs Interval {
*     int start, end;
*     Interval(int start, int end) {
*         this.start = start;
*         this.end = end;
*     }
*/

class Solution {
/**
* Insert newInterval into intervals.
* @param intervals: Sorted interval list.
* @param newInterval: A new interval.
* @return: A new sorted interval list.
*/
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
ArrayList<Interval> result = new ArrayList<Interval>();

if(intervals==null || intervals.size()==0){
return result;
}

for(Interval v:intervals){
if(newInterval == null)
else {
if(newInterval.end < v.start){
newInterval = null;
}
else if(newInterval.start > v.end)
else {
newInterval.start = Math.min(newInterval.start,v.start);
newInterval.end = Math.max(newInterval.end,v.end);
}
}
}

if(newInterval != null)