# Insert Interval

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].

/**
* 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) {
return intervals;
}

int i = 0;
while (i < intervals.size() && intervals.get(i).end < newInterval.start) {
i++;
}

if (i < intervals.size()) {
newInterval.start = Math.min(intervals.get(i).start, newInterval.start);
}

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()) {
i++;
}

return res;
}
}

#### Insert Interval -- LeetCode

2014-03-27 01:15:48

#### 57 Insert Interval

2015-10-11 17:23:42

#### LeetCode --- 57. Insert Interval

2015-03-14 23:10:32

#### 【LeetCode】Insert Interval 解题报告

2015-04-07 17:28:16

#### leetCode 57.Insert Interval (插入区间) 解题思路和方法

2015-07-15 14:11:02

#### Leetcode #57. Insert Interval 间隔插入 解题报告

2016-04-27 23:56:44

#### [Java]LeetCode57 Insert Interval

2015-08-18 20:52:56

#### Insert Interval(区间插入)

2014-02-24 15:41:22

#### Java Insert Interval(插入间隔)

2014-07-17 16:22:11

#### leetcode -- Insert Interval -- 重点

2015-12-22 20:27:03