# 57. Insert Interval

## 1.問題

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

![](/files/-LNblKMJ5hq2Ion-m-oH)

## 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;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/57.-insert-interval.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
