# 57. Insert Interval

**<font color=red>难度:Hard<font>**

## 刷题内容
> 原题连接

* https://leetcode.com/problems/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:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
```

> 思路
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******

先计算出新区间在原先区间数组中的位置。遍历数组，依次比较两个区间。记录 l 和r。分别代表了要添加的区间的起点和终点。得到位置之后，找到 intervals[i].end < l,添加进返回数组，接着再添加区间[l,r]。最后添加 intervals[i].start > r的区间。 

```cpp
/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
         int beg = newInterval.start,en = newInterval.end,l = beg,r = en;
        int comp = beg;
        for(int i = 0;i < intervals.size();++i)
        {
            if(comp < intervals[i].start)
            {
                comp == beg ? l = beg : r = en;
                comp = comp == beg ? en : beg;
                if(comp == en && en < intervals[i].start)
                {
                    r = en;
                    break;
                }
                if(comp == beg)
                    break;
            }
            if(comp <= intervals[i].end)
            {

                comp == beg ? l = intervals[i].start : r = intervals[i].end;
                comp = comp == beg ? en : beg;
                if(comp == en && en <= intervals[i].end)
                {
                    r = intervals[i].end;
                    break;
                }
                if(comp == beg)
                    break;
            }
        }
        int i = 0;
        vector<Interval> ans;
        for(;i < intervals.size();++i)
            if(intervals[i].end < l)
                ans.push_back(intervals[i]);
            else
                break;
        Interval i1(l,r);
        ans.push_back(i1);
        for(;i < intervals.size();++i)
            if(intervals[i].start > r)
                break;
        for(;i < intervals.size();++i)
            ans.push_back(intervals[i]);
        return ans;
    }
};
```