-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path56.py
55 lines (37 loc) · 1.4 KB
/
56.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. Merge Intervals
Created on 2024-12-24 15:45:01
@author: MilkTea_shih
'''
#%% Packages
#%% Variable
#%% Functions
class Solution_reference:
#Time: O(n * log(n) + n)
#Space: O(1) #replace the non-overlapping interval in-place
def merge(self, intervals: list[list[int]]) -> list[list[int]]:
intervals.sort(key=lambda x: x[0]) #sorted with the first element
k: int = 0 #non-overlapping interval count
for interval in intervals[1:]:
if interval[0] <= intervals[k][1]: #overlapping intervals
intervals[k][1] = max(intervals[k][1], interval[1])
else:
k += 1 #non-overlapping intervals
intervals[k] = interval #replace in-place
return intervals[:k + 1]
class Solution:
#Time: O(n * log(n) + n)
#Space: O(n)
def merge(self, intervals: list[list[int]]) -> list[list[int]]:
intervals.sort(key=lambda x: x[0]) #sorted with the first element
result: list[list[int]] = [intervals[0]]
for interval in intervals[1:]:
if interval[0] <= result[-1][1]: #overlapping intervals
result[-1][1] = max(result[-1][1], interval[1])
else:
result.append(interval) #non-overlapping intervals
return result
#%% Main Function
#%% Main
if __name__ == '__main__':
pass
#%%