generated from projeto-de-algoritmos-2024/RepositorioTemplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem218.py
48 lines (36 loc) · 1.28 KB
/
problem218.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
class Solution:
def getSkyline(self, buildings):
return self.divideAndConquer(buildings)
def divideAndConquer(self, buildings):
if not buildings:
return []
if len(buildings) == 1:
start, end, height = buildings[0]
return [[start, height], [end, 0]]
mid = len(buildings) // 2
left_skyline = self.divideAndConquer(buildings[:mid])
right_skyline = self.divideAndConquer(buildings[mid:])
return self.mergeSkylines(left_skyline, right_skyline)
def mergeSkylines(self, left, right):
h1 = h2 = 0
i = j = 0
merged = []
while i < len(left) and j < len(right):
if left[i][0] < right[j][0]:
x, h1 = left[i]
i += 1
elif left[i][0] > right[j][0]:
x, h2 = right[j]
j += 1
else:
x = left[i][0]
h1 = left[i][1]
h2 = right[j][1]
i += 1
j += 1
max_height = max(h1, h2)
if not merged or merged[-1][1] != max_height:
merged.append([x, max_height])
merged.extend(left[i:])
merged.extend(right[j:])
return merged