56. &57 Merge Intervals

2018-03-13  本文已影响0人  Jonddy
题目要求:

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

解题思路:
代码:
# 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].
#
class Interval(object):
    def __init__(self, s=0, t=0):
        self.start = s
        self.end = t

    def __repr__(self):
        return "[{}, {}]".format(self.start, self.end)


class Solution(object):
    def merge(self, intervals):
        """
        :param intervals: List[Interval]
        :return: List[Interval]
        """
        if not intervals:
            return intervals
        intervals.sort(key=lambda interval: interval.start)
        result = [intervals[0]]

        for i in range(1, len(intervals)):
            pre, current = result[-1], intervals[i]
            if current.start <= pre.end:
                pre.end = max(current.end, pre.end)  # 取其中最大值的值很重要
            else:
                result.append(current)
        return result

if __name__ == "__main__":
    print(Solution().merge([Interval(1, 3), Interval(2, 3), Interval(8, 10), Interval(15, 18)]))



上一篇下一篇

猜你喜欢

热点阅读