合并区间
合并区间
http://www.nowcoder.com/questionTerminal/69f4e5b7ad284a478777cb2a17fb5e6a
给出一组区间,请合并所有重叠的区间。
例如,
给出[1,3],[2,6],[8,10],[15,18],
返回[1,6],[8,10],[15,18].
写的不好看,但很intuitive 23333
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 if len(intervals) <= 1: return intervals intervals.sort(key = lambda x : x.start) ans = [] for i, interval in enumerate(intervals): if i == 0: begin = interval.start; end = interval.end continue if interval.start <= end: end = max(end, interval.end) else: ans.append(Interval(begin, end)) begin = interval.start; end = interval.end if i == len(intervals) - 1: ans.append(Interval(begin, end)) return ans