forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
average-height-of-buildings-in-each-segment.py
57 lines (52 loc) · 1.61 KB
/
average-height-of-buildings-in-each-segment.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
# Time: O(nlogn)
# Space: O(n)
class Solution(object):
def averageHeightOfBuildings(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
points = []
for x, y, h in buildings:
points.append((x, 1, h))
points.append((y, -1, h))
points.sort()
result = []
total = cnt = 0
prev = -1
for curr, c, h in points:
if cnt and curr != prev:
if result and result[-1][1] == prev and result[-1][2] == total//cnt:
result[-1][1] = curr
else:
result.append([prev, curr, total//cnt])
total += h*c
cnt += c
prev = curr
return result
# Time: O(nlogn)
# Space: O(n)
import collections
class Solution2(object):
def averageHeightOfBuildings(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
count = collections.defaultdict(lambda: (0, 0))
for x, y, h in buildings:
count[x] = (count[x][0]+1, count[x][1]+h)
count[y] = (count[y][0]-1, count[y][1]-h)
result = []
total = cnt = 0
prev = -1
for curr, (c, h) in sorted(count.iteritems()):
if cnt:
if result and result[-1][1] == prev and result[-1][2] == total//cnt:
result[-1][1] = curr
else:
result.append([prev, curr, total//cnt])
total += h
cnt += c
prev = curr
return result