LeetCode---56. Merge Intervals

题目

给出一个间隔的数组,合并所有重叠的间隔。如:
Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]

Python题解

class Solution(object):
    def merge(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[Interval]
        """
        if not intervals:
            return []
        intervals = sorted(intervals, key=lambda val:val.start)
        cur = intervals[0]
        idx = 1
        res = []
        while idx < len(intervals):
            if self.overlap(cur, intervals[idx]):
                cur = self.combine(cur, intervals[idx])
            else:
                res.append(cur)
                cur = intervals[idx]
            idx += 1
        res.append(cur)
        return res


    def overlap(self, a, b):
        return a.end >= b.start

    def combine(self, a, b):
        return Interval(min(a.start, b.start), max(a.end, b.end))

猜你喜欢

转载自blog.csdn.net/leel0330/article/details/80492823