# 57. Insert Interval

## 1.問題

* 給予一個不重疊的intervals list並插入一個新的interval, 必要時必須融合intervals

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LNbfaAKz0WhJWb-rltV%2F-LNblKMJ5hq2Ion-m-oH%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-30%20%E4%B8%8A%E5%8D%887.58.36.png?alt=media\&token=80499f83-c480-41fd-b347-3abb6ce294b9)

## 2.想法

* 提問: interval間是否已排序?
* function header, parameter
* test input
*   說明想法 **(同56.Merge Interval)**

    * 必須先排序Interval: overwrite sort operation

    ```
    //define sort operation
    struct IntervalKey {
            inline bool operator() (const Interval &pLHS, const Interval &pRHS) {
                return pLHS.start < pRHS.start;
            }
        };

    //sort vector
    sort(intervals.begin(), intervals.end(), IntervalKey());
    ```

    * 比較Interval\[i]與interval\[i - 1]:
      * 如果有重疊, 則讓interval\[cnt].end = interval\[i].end
      * 不然則將interval\[i]加入
* 測試計算複雜度

## 3.程式碼

```
/**
 * 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:
    struct IntervalKey{
        inline bool operator() (const Interval& pLHS, const Interval& pRHS) {
            return pLHS.start < pRHS.start;
        }
    };
    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
        vector<Interval> res;
        int size = intervals.size();
        if (size == 0) {
            res.push_back(newInterval);
            return res;
        }
        intervals.push_back(newInterval);
        sort(intervals.begin(), intervals.end(), IntervalKey());
        int cnt = 0;
        for (int i = 1; i < size + 1; i++) {
            if (intervals[i].start <= intervals[cnt].end && intervals[i].end >= intervals[cnt].start) {
                intervals[cnt].end = max(intervals[cnt].end, intervals[i].end);
            } else {
                ++cnt;
                intervals[cnt].start = intervals[i].start;
                intervals[cnt].end = intervals[i].end;
            }
        }
        
        res.assign(intervals.begin(), intervals.begin() + cnt + 1);
        return res;
    }
};
```
