LeetCode刷题记录——第56题(合并两个有序数组)

题目描述

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

示例 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] 可被视为重叠区间。

思路分析

  • 核心思路:按照每个子列表中第0个元素进行排序,以示例1为例,比较3和2的大小,如果3大于2说明需要合并,合并为3和6中更大的那个数字。

代码示例

class Solution(object):
    def merge(self, intervals):
        """
        :type intervals: List[List[int]]
        :rtype: List[List[int]]
        """
        res = []
        intervals.sort()   #默认为0,所以是根据第一个元素排序
        for i in intervals:
            if not res or res[-1][1] < i[0]:
                res.append(i)
            else:
                res[-1][1] = max(res[-1][1],i[1])
        return res

你可能感兴趣的:(菜鸟的LeetCode刷题记录)