56. Merge Intervals

class Solution(object):
    def merge(self, intervals):
        # 思路:
        # 1.对start和end分别排序,排序完构成的pair对和原先的pair对结果是一致的
        # 2.while循环i从第一个遍历到最后一个pair
        # 如果下一个的start比当前的end要大(或者等于),i+=1
        
        # 注意:
        # 1.sorted之后需要赋值回去
        # start = sorted(start)
        # 2.内层循环是小于"或等于"

        start, end = [], []
        for pair in intervals:
            start.append(pair[0])
            end.append(pair[1])
        start = sorted(start)
        end = sorted(end)
        res = []
        i = 0
        while i < len(start):
            s = start[i]
            while i < len(start) - 1 and start[i+1] <= end[i]:
                i += 1
            e = end[i]
            i += 1
            res.append([s,e])
        return res

s = Solution()
res = s.merge([[1,4],[0,4]])
print(res)

你可能感兴趣的:(56. Merge Intervals)