zl程序教程

您现在的位置是:首页 >  其它

当前栏目

leetcode56. 合并区间

合并 区间
2023-09-27 14:25:55 时间

给出一个区间的集合,请合并所有重叠的区间。

示例 1:

输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:

输入: [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。

思路:字符串和数组的题用py是真的爽啊。

按区间左边那个数字排序,依次判断能否合并即可。(如果排第1的不能和排第2的合并,那么它也不可能和排第三的合并,因为是按区间左边那个数字排序的)

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        res = []
        intervals.sort()
        for i in intervals:
            if not res or res[-1][1] < i[0]:
                res.append(i)
            else:
                res[-1][1] = max(i[1],res[-1][1])
        return res