-
Notifications
You must be signed in to change notification settings - Fork 17
/
insert-interval.py
77 lines (56 loc) · 1.89 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from typing import List
class Solution:
def insert(
self, intervals: List[List[int]], newInterval: List[int]
) -> List[List[int]]:
intervals.append(newInterval)
intervals.sort()
result: List[List[int]] = []
for start, end in intervals:
if result and result[-1][1] >= start:
if result[-1][1] < end:
result[-1][1] = end
else:
result.append([start, end])
return result
class Solution1:
def insert(
self, intervals: List[List[int]], newInterval: List[int]
) -> List[List[int]]:
new_interval = newInterval
result = []
pos = 0
while pos < len(intervals):
cur_begin, cur_end = tuple(intervals[pos])
new_begin, new_end = tuple(new_interval)
if cur_end < new_begin:
result.append(intervals[pos])
elif new_end < cur_begin:
break
else:
new_interval = [min(new_begin, cur_begin), max(new_end, cur_end)]
pos += 1
result.append(new_interval)
result += intervals[pos:]
return result
class TestSolution:
def setup(self):
self.sol = Solution()
def test_empty(self):
assert self.sol.insert([], [1, 2]) == [[1, 2]]
def test_case1(self):
assert self.sol.insert([[1, 3], [6, 9]], [2, 5]) == [[1, 5], [6, 9]]
def test_case2(self):
assert self.sol.insert([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]) == [
[1, 2],
[3, 10],
[12, 16],
]
def test_case3(self):
assert self.sol.insert([[1, 3], [6, 9]], [-1, 0]) == [[-1, 0], [1, 3], [6, 9]]
def test_case4(self):
assert self.sol.insert([[1, 3], [6, 9]], [50, 100]) == [
[1, 3],
[6, 9],
[50, 100],
]