#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
56:merge intervals
https://oj.leetcode.com/problems/merge-intervals/
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].
===comments by dabay===
This problem is relatively simple to think about and annoyed when realized.
The trick is to insert the existing sequence into a benchmark interval front, cross, and back, rather than inserting it into an existing sequence.
For each of the interval in a sequence,
-If its end is smaller than the start of the benchmark, insert it into the front
-If it's start is larger than the end of the benchmark, insert it into the back
-If it intersects with the benchmark, update the start and end of the benchmark
‘‘‘
# Definition for an interval.
Class Interval:
def __init__ (self, s=0, e=0):
Self.start = S
Self.end = E
Class Solution:
# @param intervals, a list of Interval
# @return A list of Interval
def merge (self, intervals):
def insert (interval, merged):
new_merged = []
i = 0
s = Interval.start
E = Interval.end
While I < Len (merged):
If Merged[i].end < s:
New_merged.append (Merged[i])
i = i + 1
Continue
If E < merged[i].start:
new_merged = new_merged + [Interval (S, e)] + merged[i:]
Break
s = min (s, merged[i].start)
E = Max (E, merged[i].end)
i = i + 1
Else
New_merged.append (Interval (S, e))
Return new_merged
If Len (intervals) <= 1:
return intervals
merged = [Intervals[0]]
i = 1
While I < Len (intervals):
merged = insert (Intervals[i], merged)
i = i + 1
Return merged
def main ():
Sol = solution ()
I1 = Interval (2,3)
I2 = Interval (4,5)
i3 = Interval (2,2)
I4 = Interval (15,18)
intervals = [I1,I2,I3,I4]
intervals = Sol.merge (intervals)
For interval in intervals:
Print "[%s,%s]"% (Interval.start, interval.end),
Print
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]56:merge intervals