LintCode:合并区间

来源:互联网 发布:美工要学哪些 编辑:程序博客网 时间:2024/06/13 15:38

LintCode:合并区间

先排序,再逐个合并

"""Definition of Interval.class Interval(object):    def __init__(self, start, end):        self.start = start        self.end = end"""class Solution:    # @param intervals, a list of Interval    # @return a list of Interval    def merge(self, intervals):        # write your code here        if len(intervals) == 0 or len(intervals) <= 1:            return intervals        self.L = intervals        self.quick_sort(self.L, 0, len(intervals)-1)        ans = []        while len(self.L) > 1:            while len(self.L) > 1 and self.L and self.L[0].end >= self.L[1].start:                if self.L[0].end <= self.L[1].end:#                    print 'Ok'                    self.L[0].end = self.L[1].end                    self.L.remove(self.L[1])                else:                    self.L.remove(self.L[1])            ans.append(self.L[0])            self.L.remove(self.L[0])        if self.L:            ans.append(self.L[0])        return ans    def quick_sort(self, L, low, high):        if low >= high:            return        i = low        j = high        tmp = L[i]        while i < j:            while i < j and L[j].start >= tmp.start:                j -= 1            L[i] = L[j]            while i < j and L[i].start <= tmp.start:                i += 1            L[j] = L[i]        L[i] = tmp        self.quick_sort(L, low, i-1)        self.quick_sort(L, i+1, high)
0 0
原创粉丝点击