|
| 1 | +# Time: O(nlogn) |
| 2 | +# Space: O(n) |
| 3 | + |
| 4 | +class Solution(object): |
| 5 | + def averageHeightOfBuildings(self, buildings): |
| 6 | + """ |
| 7 | + :type buildings: List[List[int]] |
| 8 | + :rtype: List[List[int]] |
| 9 | + """ |
| 10 | + points = [] |
| 11 | + for x, y, h in buildings: |
| 12 | + points.append((x, 1, h)) |
| 13 | + points.append((y, -1, h)) |
| 14 | + points.sort() |
| 15 | + result = [] |
| 16 | + total = cnt = 0 |
| 17 | + prev = -1 |
| 18 | + for curr, c, h in points: |
| 19 | + if cnt and curr != prev: |
| 20 | + if result and result[-1][1] == prev and result[-1][2] == total//cnt: |
| 21 | + result[-1][1] = curr |
| 22 | + else: |
| 23 | + result.append([prev, curr, total//cnt]) |
| 24 | + total += h*c |
| 25 | + cnt += c |
| 26 | + prev = curr |
| 27 | + return result |
| 28 | + |
| 29 | + |
| 30 | +# Time: O(nlogn) |
| 31 | +# Space: O(n) |
| 32 | +import collections |
| 33 | + |
| 34 | + |
| 35 | +class Solution2(object): |
| 36 | + def averageHeightOfBuildings(self, buildings): |
| 37 | + """ |
| 38 | + :type buildings: List[List[int]] |
| 39 | + :rtype: List[List[int]] |
| 40 | + """ |
| 41 | + count = collections.defaultdict(lambda: (0, 0)) |
| 42 | + for x, y, h in buildings: |
| 43 | + count[x] = (count[x][0]+1, count[x][1]+h) |
| 44 | + count[y] = (count[y][0]-1, count[y][1]-h) |
| 45 | + points = sorted(count.iteritems()) |
| 46 | + result = [] |
| 47 | + total = cnt = 0 |
| 48 | + prev = -1 |
| 49 | + for curr, (c, h) in points: |
| 50 | + if cnt: |
| 51 | + if result and result[-1][1] == prev and result[-1][2] == total//cnt: |
| 52 | + result[-1][1] = curr |
| 53 | + else: |
| 54 | + result.append([prev, curr, total//cnt]) |
| 55 | + total += h |
| 56 | + cnt += c |
| 57 | + prev = curr |
| 58 | + return result |
0 commit comments