# 56. Merge Intervals

## 1.問題

* 給予一個區間組成的集合, merge所有重疊的區間

![](/files/-LJ2LHGylop-p1EPZj9w)

## 2.想法

* 提問: interval間是否已排序?
* parameter
  * Interval list
* test input
* 說明想法

  * 必須先排序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\[cnt]:
    * 如果有重疊, 則讓interval\[cnt].end = interval\[i].end
    * 不然則將cnt++, 讓interval\[i]加入新的interval\[cnt]
* 測試計算複雜度

## 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& in1, const Interval& in2) {
            return in1.start < in2.start;
        }
    };
    
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> res;
        if (intervals.size() == 0) {
            return res;
        }
        sort(intervals.begin(), intervals.end(), intervalKey());
        int cnt = 0, n = intervals.size();
        res.push_back(intervals[0]);
        for (int i = 1; i < n; i++) {
            if (intervals[i].start <= res[cnt].end) {
                res[cnt].end = max(intervals[i].end, res[cnt].end);
            } else {
                cnt++;
                res.push_back(intervals[i]);
            }
        }
        
        return res;
    }
};
```

## 4.Performance

![](/files/-LJ2MVhW0o2cqcDD8YoY)


---

# 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/56.-merge-intervals.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.
