Insert Interval
Description:
Given a non-overlapping interval list which is sorted by start point.
Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).
Example
Insert (2, 5) into [(1,2), (5,9)], we get [(1,9)].
Insert (3, 4) into [(1,2), (5,9)], we get [(1,2), (3,4), (5,9)].
Code:
"""
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
"""
@param intervals: Sorted interval list.
@param newInterval: new interval.
@return: A new interval list.
"""
def insert(self, intervals, newInterval):
# write your code
intervals.append(newInterval)
intervals.sort(key = lambda x: x.start)
res = []
res.append(intervals[0])
l = len(intervals)
for i in range(1,l):
cur = len(res)
if res[cur-1].end >= intervals[i].start:
res[cur-1].end = max(res[cur-1].end, intervals[i].end)
else:
res.append(intervals[i])
return res