代码改变世界

LeetCode 56. 56. Merge Intervals 20170508

2017-05-08 17:07  方小呆dai  阅读(307)  评论(0编辑  收藏  举报

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

题目大意:给出一个区间的集合,将重叠的区间合并

解题思路:

1、将集合内的区间按照区间的起始位置的大小从小到大排序

2、用一个新的list来保存合并后的结果,先放入起始位置最小的区间

3、接下来每次取原集合中起始位置最小的区间a,跟新的list中起始位置最大的区间b对比,如果b的结束位置比a的起始位置要大的话,说明两者有重叠,

     所以接下来只要对比a和b的结束位置谁大,就把大的值作为b的新的结束位置。如果b的结束位置比a的起始位置小的话,说明两者没有重叠,则直接把a添加到新的list中。

# Definition for an interval.
# class Interval(object):
#    def __init__(self, s=0, e=0):
#   self.start = s
#   self.end = e

class Solution(object):
  def merge(self, intervals):
  """
  :type intervals: List[Interval]
  :rtype: List[Interval]
  """
  newcollection = []
  if len(intervals) == 0:
    return newcollection
  intervals.sort(key=lambda x: x.start)
  newcollection.append(intervals[0])
  for interval in intervals[1:]:
    length = len(newcollection)
    prev = newcollection[-1]
    if newcollection[length - 1].end >= interval.start:
      newcollection[length - 1].end = max(newcollection[length - 1].end, interval.end)
    else:
      newcollection.append(interval)
    return newcollection