---
# System prepended metadata

title: 57. Insert Interval
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}
   
</style>

###### tags: `Leetcode`

# 57. Insert Interval

###### Link : https://leetcode.com/problems/insert-interval/description/

## 題目
插入一個範圍，並把重疊的範圍合併
## 程式碼 

```cpp=
class Solution {
public:
    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
        int locate = intervals.size();
        for(int i = 0;i < intervals.size();i++){
            if(intervals[i][0] > newInterval[0]){
                locate = i;
                break;
            }
        }
        intervals.insert(intervals.begin() + locate, newInterval);//將newInterval和intervals按照順序合併
        for(int i = 0;i < intervals.size()-1;i++){
            while(i+1 < intervals.size() && intervals[i][1] >= intervals[i+1][0]){//如果有重疊
                intervals[i][1] = (intervals[i+1][1] > intervals[i][1])?intervals[i+1][1]:intervals[i][1];//將比較大的下界設為前者的下界
                intervals.erase(begin(intervals)+i+1);//刪除後者
            }
        }
        return intervals;
    }
};
```