# leetcode 57: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].

class Solution {
public:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
int size = intervals.size();
vector<Interval> result;
if (size == 0)
{
result.push_back(newInterval);
return result;
}
int i = 0,low,high;
while (i<size && intervals[i].end < newInterval.start)
{
result.push_back(intervals[i]);
++i;
}
if (i<size && newInterval.end < intervals[i].start)
result.push_back(newInterval);
else
{
low = i < size ? min(intervals[i].start, newInterval.start) : newInterval.start;
while (i < size && newInterval.end >= intervals[i].start) ++i;
high = i>0 ? max(intervals[i-1].end, newInterval.end) : newInterval.end;
Interval temp(low, high);
result.push_back(temp);
}
while (i < size)
{
result.push_back(intervals[i]);
++i;
}
return result;
}
};

class Solution {
public:
static bool comp(const Interval a, const Interval b)
{
return a.start < b.start ? 1 : 0;
}
vector<Interval> insert(vector<Interval>& intervals,Interval newInterval) {
intervals.push_back(newInterval);
vector<Interval> result;
int size = intervals.size();
if (size < 2) return intervals;
sort(intervals.begin(), intervals.end(), comp);
for (int i = 0; i<size; ++i)
{
Interval temp(intervals[i].start, intervals[i].end);
int high = intervals[i].end;
while (i < size - 1 && high >= intervals[i + 1].start)
{
if (intervals[i + 1].end > high) high = intervals[i + 1].end;
++i;
}
temp.end = high;
result.push_back(temp);
}
return result;
}
};

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

2016-04-27 23:56:44

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

2015-03-14 23:10:32

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

2015-07-15 14:11:02

#### [Java]LeetCode57 Insert Interval

2015-08-18 20:52:56

#### 57 Insert Interval

2015-10-11 17:23:42

#### Insert Interval Leetcode #57 题解[Python]

2018-05-12 11:21:45

#### LeetCode #57 | Insert Interval

2017-04-24 18:21:11

#### leetcode 57: Insert Interval

2015-09-15 08:04:52

#### leetcode || 57、Insert Interval

2015-04-01 16:06:35

#### LeetCode 57 Insert Interval

2016-11-01 15:59:36