-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0057-insert-interval.py
More file actions
43 lines (32 loc) · 1.09 KB
/
0057-insert-interval.py
File metadata and controls
43 lines (32 loc) · 1.09 KB
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
"""
57. Insert Interval
Submitted: March 15, 2026
Runtime: 0 ms (beats 100.00%)
Memory: 21.57 MB (beats 16.82%)
"""
# this solution inserts the interval and then re-merges the whole array
# can make more efficient by only re-merging w/ two adjacent elements.
import bisect
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
if not intervals:
return [newInterval]
i = bisect.insort_left(intervals, newInterval)
return self.merge(intervals)
# copied from 56 sol
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
res = []
for (start, end) in intervals:
if not res:
res.append((start, end))
continue
prev = res[-1]
prev_start, prev_end = prev
if prev_end >= start:
start = min(start, prev_start)
end = max(end, prev_end)
res[-1] = (start, end)
else:
res.append((start, end))
return res