Created
February 20, 2019 12:43
-
-
Save miguelangelgonzalez/d81ff5f0218851c27d24ccbf8ad39971 to your computer and use it in GitHub Desktop.
Given a collection of intervals, merge all overlapping intervals.
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
# https://statyang.wordpress.com/python-practice-101-merge-intervals/ | |
# Definition for an interval. | |
class Interval: | |
def __init__(self, s=0, e=0): | |
self.start = s | |
self.end = e | |
class Solution: | |
# @param {Interval[]} intervals | |
# @return {Interval[]} | |
def merge(self, intervals): | |
interv=[] | |
for i in range(len(intervals)): | |
interv.append([intervals[i].start,intervals[i].end]) | |
interv.sort() | |
res=[] | |
while(len(interv)>0): | |
if len(interv)==1: | |
res.append(interv[0]) | |
interv.pop(0) | |
continue | |
if interv[0][1]>=interv[1][0]: | |
tmp=[interv[0][0],max(interv[0][1],interv[1][1])] | |
interv[0]=tmp | |
interv.pop(1) | |
continue | |
res.append(interv[0]) | |
interv.pop(0) | |
return res | |
result = Solution().merge([Interval(1,3), Interval(2,6), Interval(8,10), Interval(15,18)]) | |
print(result) | |
#return [1,6],[8,10],[15,18]. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment