# LeetCode 筆記 :(56) Merge Intervals ###### tags: `Leetcode` Given an array of intervals where intervals`[i] = [starti, endi]`, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. * 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. ``` ## Leetcode Solution 官方的答案提供兩種不同的想法,因為Solution 2比較簡潔,所以我就簡單說明一下,先將list 針對地一個數進行排列。去比對每個list的end 是否小於下一個的start。如果是代表已經是不同區間。如果不是就進行合併。 ### Solution 2 ```python3= class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort(key=lambda x: x[0]) merged = [] for interval in intervals: # if the list of merged intervals is empty or if the current # interval does not overlap with the previous, simply append it. if not merged or merged[-1][1] < interval[0]: merged.append(interval) else: # otherwise, there is overlap, so we merge the current and previous # intervals. merged[-1][1] = max(merged[-1][1], interval[1]) return merged ``` ![](https://i.imgur.com/uR78MsM.png)