【LeetCode每天一题】Merge Intervals(合并区间)

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 considered overlapping.

思路


      这道题我当时看到之后想的的办法就是将nums中第一个添加进结果集中,然后从nums的第一个开始遍历和和res结果集中进行比较。按照这个思路当时提交之后发现输入的nums并不是有序的,因此先对其进行排序。然后得到排序之后的结果。这次在提交就解决了。 时间复杂度为O(nlogn), 空间复杂度为O(1)。

解决代码


 

 1 class Solution(object):
 2     def merge(self, nums):
 3         """
 4         :type intervals: List[List[int]]
 5         :rtype: List[List[int]]
 6         """
 7         if not nums or len(nums) < 2:     # 数量小于2个时直接返回结果
 8             return nums
 9         nums.sort()                     # 排序
10         res = [nums[0]]                 # 将nums中第一个元素添加进res中
11         for li in nums[1:]:             # 开始遍历
12             if res[-1][-1] < li[0]:      # 如果当前遍历的范围的起始值大于结果集中的最后一个范围的终止范围值。直接添加
13                 res.append(li)
14             else:
15                 res[-1][-1] = max(res[-1][-1], li[-1])    # 否则我们选择最大的值作为结束值,并改变res中的值
16         return res

 

posted @ 2019-04-20 13:21  GoodRnne  阅读(167)  评论(0编辑  收藏  举报