Leetcode 56. Merge Intervals
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:现将左右endpoint都排序,然后逐个push进入stack。如果当前的endpoint是 ], 而且之前已经连续出现两个 [。那么这个这必定是一个被覆盖的interval,所以不能push,而且要pop之前的 [。
注意一个特殊情况,[1, 4], [4, 6]。答案应当是 [1,6]。也就是如果当前为[, 前面一个是],而且两个的值相同,那么当年的不能push,前面的一个要pop掉。注意L20,对于list of lists 按照某个位置的元素排序的方法。
1 # Definition for an interval. 2 # class Interval(object): 3 # def __init__(self, s=0, e=0): 4 # self.start = s 5 # self.end = e 6 7 class Solution(object): 8 def merge(self, intervals): 9 """ 10 :type intervals: List[Interval] 11 :rtype: List[Interval] 12 """ 13 if not intervals: 14 return [] 15 16 endPoints = [] 17 for elem in intervals: 18 endPoints.append([elem.start, 'l']) 19 endPoints.append([elem.end, 'r']) 20 endPoints.sort(key=lambda x:x[0]) 21 22 stack = [] 23 for elem in endPoints: 24 if len(stack) >= 2 and stack[-1][1] == 'l' and stack[-2][1] == 'l' and elem[1] == 'r': 25 stack.pop() 26 elif stack and stack[-1][1] == 'r' and elem[1] == 'l' and elem[0]==stack[-1][0]: 27 stack.pop() 28 else: 29 stack.append(elem) 30 31 newIntervals = [ ] 32 size = len(stack)/2 33 for i in range(size): 34 Intv = Interval(0,0) 35 endPoints = stack.pop() 36 Intv.end = endPoints[0] 37 endPoints = stack.pop() 38 Intv.start = endPoints[0] 39 newIntervals.append(Intv) 40 return newIntervals
思路2: 参考http://yucoding.blogspot.com/2013/01/leetcode-question-51-merge-intervals.html
其实我们排序时只需要按照start将intervals排起来就好了。然后逐个Interval检查和前面的一个interval是不是intersec。如果有交集,那么更新前面一个interval,如果没有push当前的interval进入res。代码简洁很多。
1 class Solution(object): 2 def merge(self, intervals): 3 """ 4 :type intervals: List[Interval] 5 :rtype: List[Interval] 6 """ 7 if not intervals: 8 return [] 9 10 intervals.sort(key = lambda x:x.start) 11 12 13 res= [intervals[0]] 14 15 for i in range(1, len(intervals)): 16 cur = intervals[i] 17 if cur.start <= res[-1].end: 18 res[-1].end = max(cur.end, res[-1].end) 19 else: 20 res.append(cur) 21 return res