思路
插入区间[2, 5] 到 [[1,2], [5,9]],我们得到 [[1,9]]。
插入区间[3, 4] 到 [[1,2], [5,9]],我们得到 [[1,2], [3,4], [5,9]]。
Python
class Interval:
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 here
if not intervals:
return [newInterval]
new_intervals = []
flag = 1
for interval in intervals:
if newInterval.start < interval.start and flag:
new_intervals.append(newInterval)
flag = 0
new_intervals.append(interval)
if len(intervals) == len(new_intervals):
new_intervals.append(newInterval)
prev_interval = new_intervals[0]
for index, interval in enumerate(new_intervals[1:], 1):
if interval.start <= prev_interval.end:
temp = Interval(prev_interval.start, max(prev_interval.end, interval.end))
new_intervals.insert(index - 1, temp)
new_intervals.remove(interval)
new_intervals.remove(prev_interval)
prev_interval = temp
else:
prev_interval = interval
return new_intervals
if __name__ == "__main__":
intervals = [Interval(1, 5), Interval(7, 8), Interval(10, 13)]
newInterval = Interval(6, 6)
s = Solution()
for x in s.insert(intervals, newInterval):
print("[{0}, {1}]".format(x.start, x.end), end=" ,")