1. 程式人生 > >Leetcode_Sort --56. Merge Intervals [medium]

Leetcode_Sort --56. Merge Intervals [medium]

Given a collection of intervals, merge all overlapping intervals. 給定一個間隔集合,將間隔集合中有重疊的間隔合併

Example 1:

Input: [[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: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1
,4] and [4,5] are considerred overlapping.

Solution:

Python

class Solution:
    def merge(self, intervals):
        out = []
        for i in sorted(intervals, key=lambda i: i[0]):
            if out and i[0] <= out[-1][-1]:
                out[-1][-1] = max(out[-1][-1], i[-1])
            else
: out.append(i) return out

這個是借鑑Discuss上的程式碼,intervals是列表,其中包含了子列表。 sorted函式的key是一個匿名函式,利用intervals中的子列表的首個元素對intervals進行排序。out是待輸出的間隔序列,且其中的子列表都是已經排好序且符合題目要求的間隔序列。當拿來一個新的intervals子序列 i ,就判斷 i 的首字母和out列表中最後一個子列表的最後一個元素誰更大,如果 i 的首元素小於 out 列表中最後一個子列表的最後一個元素,就說明有間隔重疊,則out中最後一個子列表和 i 是可合併的。合併的尾元素是out最後子列表和 i 中尾元素較大的那一個,最後返回out序列就可以了。