[Leetcode]Merge Intervals

来源:互联网 发布:农村淘宝推广招聘信息 编辑:程序博客网 时间:2024/06/16 08:22

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].

要求合并若干个区间~记得先把intervals按start值排序~


# Definition for an interval.# class Interval:#     def __init__(self, s=0, e=0):#         self.start = s#         self.end = eclass Solution:    # @param intervals, a list of Interval    # @return a list of Interval    def merge(self, intervals):        if intervals is None or len(intervals) == 0:            return []        intervals.sort(key = lambda x: x.start)        #intervals.sort(cmp = lambda x, y: cmp(x.start, y.start) or (x.start == y.start and cmp(x.end,y.end)))        res = []; prev = Start = End = None        for curr in intervals:            if prev:                if curr.start <= End:                    End = max(End, curr.end)                else:                    res.append([Start, End])                    Start, End = curr.start, curr.end            else:                Start, End = curr.start, curr.end            prev = curr        res.append([Start, End])        return res

0 0
原创粉丝点击