合并区间

合并区间

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
全部评论
厉害
点赞 回复 分享
发布于 2020-12-29 17:31

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务