题解 | #合并区间#
合并区间
http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
使用if语句,看区间开始和上一个区间的末尾谁大,如果小的话就合并了,如果大的话就append
# class Interval:
# def __init__(self, a=0, b=0):
# self.start = a
# self.end = b
#
#
# @param intervals Interval类一维数组
# @return Interval类一维数组
#
class Solution:
def merge(self , intervals ):
# write code here
intervals.sort(key=lambda x:x.start)
ans = []
if len(intervals) == 0:
return ans
for i in range(1,len(intervals)):
if intervals[i].start <= intervals[i-1].end:
intervals[i].start = min(intervals[i-1].start, intervals[i].start)
intervals[i].end = max(intervals[i-1].end, intervals[i].end)
else:
ans.append(intervals[i-1])
ans.append(intervals[len(intervals)-1])
return ans