这题除了沿用上次的merge interval根据返回值来判断,然后不断进行merge的方法外,还可以有通过观察插入的位置来决定覆盖。代码如下:
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
if intervals == []:
return [newInterval]
list1 = []
for i in intervals:
list1.append(i.start)
list1.append(i.end)
list1.append(newInterval.start)
list1.append(newInterval.end)
list1.sort()
a = list1.index(newInterval.start)
b = list1.index(newInterval.end)
if a % 2 == 0:
if b % 2 == 0:
list1 = list1[:a + 1] + list1[b+ 1:]
else:
if b != len(list1) - 1:
if list1[b] != list1[b + 1]:
list1 = list1[:a + 1] + list1[b:]
else:
list1 = list1[:a + 1] + list1[b + 2:]
else:
list1 = list1[:a + 1] + list1[b:]
else:
if b % 2 == 0:
list1 = list1[:a] + list1[b + 1:]
else:
if b != len(list1) - 1:
if list1[b] != list1[b + 1]:
list1 = list1[:a] + list1[b:]
else:
list1 = list1[:a] + list1[b + 2:]
else:
list1 = list1[:a] + list1[b:]
list2 = []
for i in range(0, len(list1), 2):
list2.append(Interval(list1[i], list1[i + 1]))
return list2