forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert-interval.py
More file actions
23 lines (19 loc) · 773 Bytes
/
insert-interval.py
File metadata and controls
23 lines (19 loc) · 773 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
ans = []
i = 0
#add intervals before newInterval
while i<len(intervals) and intervals[i][1]<newInterval[0]:
ans.append(intervals[i])
i += 1
#add newInterval and merge the overlapped
ans.append(newInterval)
while i<len(intervals) and intervals[i][0]<=ans[-1][1]:
ans[-1][0] = min(ans[-1][0], intervals[i][0])
ans[-1][1] = max(ans[-1][1], intervals[i][1])
i += 1
#add intervals after newInterval
while i<len(intervals):
ans.append(intervals[i])
i += 1
return ans