LeetCode C++ 56. Merge Intervals【排序/陣列】中等

myRealization發表於2020-10-18

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

Constraints: intervals[i][0] <= intervals[i][1]

題意:給出一個區間的集合,請合併所有重疊的區間。


解法1 排序

對區間陣列,按照左端點從小到大排序,左端點相同則按照右端點從小到大排序。然後從前往後掃描,如果當前區間的左端點大於結果陣列尾元素的右端點,則不存在重疊,無需區間合併;否則比較大小,並用當前區間的右端點更新結果陣列尾元素的右端點,進行區間合併。

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        sort(intervals.begin(), intervals.end());
        vector<vector<int>> ans;
        for (auto &i : intervals) { 
            if (ans.empty() || i[0] > ans.back()[1]) ans.push_back(i); //不重疊
            else ans.back()[1] = max(i[1], ans.back()[1]); //i[0]<=ans.back()[1]
        }
        return ans;
    }
};

提交後效率如下:

執行用時:60 ms, 在所有 C++ 提交中擊敗了49.30% 的使用者
記憶體消耗:14 MB, 在所有 C++ 提交中擊敗了51.16% 的使用者

相關文章