Skip to content

Commit

Permalink
update merge_intervals
Browse files Browse the repository at this point in the history
  • Loading branch information
yunshuipiao committed Feb 1, 2018
1 parent dc778bc commit 63ebe78
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions array/merge_intervals.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,24 @@ def print_intervals(intervals):
res.append('['+str(i.start)+','+str(i.end)+']')
print("".join(res))

def merge_intervals(l):
#sort
if l is None:
return None
l.sort(key=lambda i: i[0])
out = [l.pop(0)]
for i in l:
if out[-1][-1] >= i[0]:
out[-1][-1] = i[-1]
else:
out.append(i)
return out

if __name__ == "__main__":
given = [[1,3],[2,6],[8,10],[15,18]]
intervals = []
for l, r in given:
intervals.append(Interval(l,r))
print_intervals(intervals)
print_intervals(merge(intervals))
print(merge_intervals[given])

0 comments on commit 63ebe78

Please sign in to comment.