|
| 1 | +# time complexity: O(nlogn) |
| 2 | +# space complexity: O(n) |
| 3 | +import bisect |
| 4 | +from collections import defaultdict |
| 5 | +from typing import List |
| 6 | + |
| 7 | + |
| 8 | +class Solution: |
| 9 | + def countCoveredBuildings(self, n: int, buildings: List[List[int]]) -> int: |
| 10 | + rowMap = defaultdict(list) |
| 11 | + colMap = defaultdict(list) |
| 12 | + |
| 13 | + for x, y in buildings: |
| 14 | + rowMap[x].append(y) |
| 15 | + colMap[y].append(x) |
| 16 | + |
| 17 | + for row in rowMap: |
| 18 | + rowMap[row].sort() |
| 19 | + for col in colMap: |
| 20 | + colMap[col].sort() |
| 21 | + |
| 22 | + result = 0 |
| 23 | + for x, y in buildings: |
| 24 | + row = rowMap[x] |
| 25 | + col = colMap[y] |
| 26 | + |
| 27 | + rowIdx = bisect.bisect_left(row, y) |
| 28 | + hasLeft = rowIdx > 0 |
| 29 | + hasRight = rowIdx < len(row) - 1 |
| 30 | + |
| 31 | + colIdx = bisect.bisect_left(col, x) |
| 32 | + hasAbove = colIdx > 0 |
| 33 | + hasBelow = colIdx < len(col) - 1 |
| 34 | + |
| 35 | + if hasLeft and hasRight and hasAbove and hasBelow: |
| 36 | + result += 1 |
| 37 | + |
| 38 | + return result |
| 39 | + |
| 40 | + |
| 41 | +n = 3 |
| 42 | +buildings = [[1, 2], [2, 2], [3, 2], [2, 1], [2, 3]] |
| 43 | +print(Solution().countCoveredBuildings(n, buildings)) |
| 44 | +n = 3 |
| 45 | +buildings = [[1, 1], [1, 2], [2, 1], [2, 2]] |
| 46 | +print(Solution().countCoveredBuildings(n, buildings)) |
| 47 | +n = 5 |
| 48 | +buildings = [[1, 3], [3, 2], [3, 3], [3, 5], [5, 3]] |
| 49 | +print(Solution().countCoveredBuildings(n, buildings)) |
0 commit comments