题解 | #合并区间#

合并区间

http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a

没有奇技淫巧,先对start排序,再逐个比较

# 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 ):
        if len(intervals) <= 1:
            return intervals      
        # write code here              
        intervals.sort(key = lambda x:x.start)


        n = len(intervals)
        res = []
        curr = intervals[0]

        for i in range(1, n):
            temp = intervals[i]           
            if temp.start > curr.end: # not overlap
                res.append(Interval(a=curr.start, b=curr.end))                               
                curr = temp
            elif curr.end < temp.end: # overlap and merge
                curr.end = temp.end
            if i == n-1:
                res.append(Interval(a=curr.start, b=curr.end))       
        return res


            #update curr

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务