Created
September 3, 2015 05:14
-
-
Save jones/444fdf504c1b02f41a5d to your computer and use it in GitHub Desktop.
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].
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Definition for an interval. | |
# class Interval(object): | |
# def __init__(self, s=0, e=0): | |
# self.start = s | |
# self.end = e | |
class Solution(object): | |
def merge(self, intervals): | |
""" | |
:type intervals: List[Interval] | |
:rtype: List[Interval] | |
""" | |
intervals = sorted(intervals, key=lambda a: a.start) | |
i = 0 | |
while i < len(intervals) - 1: | |
a = intervals[i] | |
b = intervals[i+1] | |
if a.end >= b.start: | |
intervals[i] = Interval(a.start, max(a.end, b.end)) | |
intervals.pop(i+1) | |
else: | |
i += 1 | |
return intervals | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment