[LeetCode] Insert Intervals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""
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 here
start = newInterval.start
end = newInterval.end
# find start
pos = -1
for i in range(len(intervals)):
if intervals[i].end == start:
pos = i + 1
break
elif intervals[i].start >= start:
pos = i
break
if pos == -1:
# append
intervals.append(newInterval)
intervals.insert(pos, newInterval)
i = 1
while i < len(intervals):
if intervals[i].start < intervals[i-1].end and intervals[i].end < intervals[i-1].end:
del intervals[i]
continue
if intervals[i].start <= intervals[i-1].end and intervals[i].end >= intervals[i-1].end:
intervals[i-1].end = intervals[i].end
del intervals[i]
continue
i += 1
return intervals