<p>Given an array&nbsp;of <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]]
<strong>Output:</strong> [[1,6],[8,10],[15,18]]
<strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> intervals = [[1,4],[4,5]]
<strong>Output:</strong> [[1,5]]
<strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li>
	<li><code>intervals[i].length == 2</code></li>
	<li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        vector<vector<int>> res;
        map<int, int> dataMap;  // {start, end}

        for(auto &interval : intervals){
            int start = interval[0];
            int end = interval[1];

            // 跳過無效區間
            if(start > end) continue;

            // 找到第一個起點大於等於當前區間起點的區間
            auto it = dataMap.lower_bound(start);
            
            // 向前合併
            while(it != dataMap.begin()) {
                auto prevIt = prev(it);
                if(start > prevIt->second) break;
                start = min(start, prevIt->first);
                end = max(end, prevIt->second);
                it = dataMap.erase(prevIt);
            }

            // 向後合併
            while(it != dataMap.end() && end >= it->first) {
                end = max(end, it->second);
                it = dataMap.erase(it);
            }

            // 插入合併後的區間
            dataMap[start] = end;
        }

        // 構建結果
        for(auto &[start, end] : dataMap) {
            res.push_back({start, end});
        }
        return res;
    }
};
24900