return [1,6],[8,10],[15,18].
这道题目做法有很多中,有用stack的也有直接计算的。这里我采用直接计算的方法。
1.将intervals按照start进行排序
2.然后比较start 如果有 pre.start<=post.start<=pre.end 那pre.end=max(pre.end,post.end) 否者的话就不用进行merge
因为要进行排序,所以时间复杂度为O(nlogn+n)= O(nlogn)
We need to sort the intervals based on start, then we compare pre.start with post.start and pre.end. If post.start fall in [pre.start, pre.end] we need to merge the two based on
max(pre.end,post.end)
otherwise, we add the interval to the solution directly.
The time complexity in this problem is O(nlogn)
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: # @param intervals, a list of Interval # @return a list of Interval def merge(self, intervals): solution=[] intervals.sort(key=lambda x:x.start) for index in range(len(intervals)): if solution==[]: solution.append(intervals[index]) else: size=len(solution) if solution[size-1].start<=intervals[index].start<=solution[size-1].end: solution[size-1].end=max(solution[size-1].end,intervals[index].end) else: solution.append(intervals[index]) return solution