forked from mission-peace/interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathskylinedrawing.py
More file actions
62 lines (48 loc) · 1.82 KB
/
skylinedrawing.py
File metadata and controls
62 lines (48 loc) · 1.82 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# https://leetcode.com/problems/the-skyline-problem/
class BuildingPoint(object):
def __init__(self, point, is_start, height):
self.point = point;
self.is_start = is_start
self.height = height
def __lt__(self, other):
if self.point != other.point:
return self.point < other.point
else:
if self.is_start:
h1 = -self.height
else:
h1 = self.height
if other.is_start:
h2 = -other.height;
else:
h2 = other.height
return h1 < h2
def get_skyline(buildings):
building_points = []
for building in buildings:
building_points.append(BuildingPoint(building[0], True, building[2]))
building_points.append(BuildingPoint(building[1], False, building[2]))
building_points = sorted(building_points)
queue = {}
queue[0] = 1
prev_max_height = 0
result = []
for building_point in building_points:
if building_point.is_start:
if building_point.height in queue:
queue[building_point.height] = queue[building_point.height] + 1
else:
queue[building_point.height] = 1
else:
if queue[building_point.height] == 1:
del queue[building_point.height]
else:
queue[building_point.height] = queue[building_point.height] - 1
current_max_height = max(queue.keys())
if prev_max_height != current_max_height:
result.append([building_point.point, current_max_height])
prev_max_height = current_max_height
return result
if __name__ == '__main__':
buildings = [[1, 3, 4], [3, 4, 4], [2, 6, 2], [8, 11, 4], [7, 9, 3], [10, 11, 2]]
print(get_skyline(buildings))