LeetCode 题解工作台
统计被覆盖的建筑
给你一个正整数 n ,表示一个 n x n 的城市,同时给定一个二维数组 buildings ,其中 buildings[i] = [x, y] 表示位于坐标 [x, y] 的一个 唯一 建筑。 如果一个建筑在四个方向(左、右、上、下)中每个方向上都至少存在一个建筑,则称该建筑 被覆盖 。 返回 被…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们可以将建筑按照横坐标和纵坐标进行分组,分别记录在哈希表 和 中,其中 表示所有横坐标为 的纵坐标,而 表示所有纵坐标为 的横坐标,然后我们将其进行排序。 接下来,我们遍历所有建筑,对于当前建筑 $(x, y)$,我们通过哈希表获取对应的纵坐标列表 和横坐标列表 ,并检查条件以确定建筑是否被覆盖。覆盖的条件是 $l_2[0] < x < l_2[-1]$ 且 $l_1[0] < y…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个正整数 n,表示一个 n x n 的城市,同时给定一个二维数组 buildings,其中 buildings[i] = [x, y] 表示位于坐标 [x, y] 的一个 唯一 建筑。
如果一个建筑在四个方向(左、右、上、下)中每个方向上都至少存在一个建筑,则称该建筑 被覆盖 。
返回 被覆盖 的建筑数量。
示例 1:

输入: n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]
输出: 1
解释:
- 只有建筑
[2,2]被覆盖,因为它在每个方向上都至少存在一个建筑:- 上方 (
[1,2]) - 下方 (
[3,2]) - 左方 (
[2,1]) - 右方 (
[2,3])
- 上方 (
- 因此,被覆盖的建筑数量是 1。
示例 2:

输入: n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]
输出: 0
解释:
- 没有任何一个建筑在每个方向上都有至少一个建筑。
示例 3:

输入: n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]
输出: 1
解释:
- 只有建筑
[3,3]被覆盖,因为它在每个方向上至少存在一个建筑:- 上方 (
[1,3]) - 下方 (
[5,3]) - 左方 (
[3,2]) - 右方 (
[3,5])
- 上方 (
- 因此,被覆盖的建筑数量是 1。
提示:
2 <= n <= 1051 <= buildings.length <= 105buildings[i] = [x, y]1 <= x, y <= nbuildings中所有坐标均 唯一 。
解题思路
方法一:哈希表 + 排序
我们可以将建筑按照横坐标和纵坐标进行分组,分别记录在哈希表 和 中,其中 表示所有横坐标为 的纵坐标,而 表示所有纵坐标为 的横坐标,然后我们将其进行排序。
接下来,我们遍历所有建筑,对于当前建筑 ,我们通过哈希表获取对应的纵坐标列表 和横坐标列表 ,并检查条件以确定建筑是否被覆盖。覆盖的条件是 且 ,若是,我们将答案加一。
遍历结束后,返回答案即可。
时间复杂度 ,空间复杂度 。其中 是建筑物的数量。
class Solution:
def countCoveredBuildings(self, n: int, buildings: List[List[int]]) -> int:
g1 = defaultdict(list)
g2 = defaultdict(list)
for x, y in buildings:
g1[x].append(y)
g2[y].append(x)
for x in g1:
g1[x].sort()
for y in g2:
g2[y].sort()
ans = 0
for x, y in buildings:
l1 = g1[x]
l2 = g2[y]
if l2[0] < x < l2[-1] and l1[0] < y < l1[-1]:
ans += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on grouping and sorting: O(b log b) where b is the number of buildings, due to sorting each axis group. Space complexity is O(b) to store hash maps of coordinates for quick neighbor lookups. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect fast identification of fully surrounded buildings using combined array scanning and hash lookups.
- question_mark
Look for efficient grouping by x and y coordinates to reduce neighbor checks.
- question_mark
Sorting within axis groups can reveal optimization awareness and understanding of the coverage pattern.
常见陷阱
外企场景- error
Forgetting to check all four directions and miscounting partially surrounded buildings.
- error
Not grouping by axis, resulting in repeated scans and time limit issues.
- error
Incorrectly handling edge buildings where one or more directions cannot have neighbors.
进阶变体
外企场景- arrow_right_alt
Count buildings with at least three neighbors instead of four.
- arrow_right_alt
Identify uncovered buildings using the same hash lookup pattern.
- arrow_right_alt
Extend to non-square grids or irregular coordinate bounds while maintaining the scanning approach.