forked from yingl/LintCodeInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsert_interval.py
32 lines (31 loc) · 1.06 KB
/
insert_interval.py
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
# -*- coding: utf-8 -*-
class Solution:
"""
Insert a new interval into a sorted non-overlapping interval list.
@param intevals: Sorted non-overlapping interval list
@param newInterval: The new interval.
@return: A new sorted non-overlapping interval list with the new interval.
"""
def insert(self, intervals, newInterval):
# write your code here
ret = []
i = 0
while i < len(intervals):
if intervals[i].start > newInterval.start:
break
i += 1
if i > 0:
ret[0:i] = intervals[0:i]
intervals[i - 1] = newInterval
start = i - 1
else:
ret.append(newInterval)
start = 0
for i in xrange(start, len(intervals)):
if (intervals[i].start >= ret[-1].start) and \
(intervals[i].start <= ret[-1].end):
if intervals[i].end > ret[-1].end:
ret[-1].end = intervals[i].end
else:
ret.append(intervals[i])
return ret