LeetCode 题解工作台
保持城市天际线
给你一座由 n x n 个街区组成的城市,每个街区都包含一座立方体建筑。给你一个下标从 0 开始的 n x n 整数矩阵 grid ,其中 grid[r][c] 表示坐落于 r 行 c 列的建筑物的 高度 。 城市的 天际线 是从远处观察城市时,所有建筑物形成的外部轮廓。从东、南、西、北四个主要方向…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
根据题目描述,我们可以将每个单元格 $(i, j)$ 的值增加至第 行的最大值和第 列的最大值中的较小值,这样可以保证不影响天际线,即每个单元格增加的高度为 $\min(\textit{rowMax}[i], \textit{colMax}[j]) - \textit{grid}[i][j]$。 因此,我们可以先遍历一次矩阵,分别计算出每行和每列的最大值,记录在数组 和 中,然后再遍历一次…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一座由 n x n 个街区组成的城市,每个街区都包含一座立方体建筑。给你一个下标从 0 开始的 n x n 整数矩阵 grid ,其中 grid[r][c] 表示坐落于 r 行 c 列的建筑物的 高度 。
城市的 天际线 是从远处观察城市时,所有建筑物形成的外部轮廓。从东、南、西、北四个主要方向观测到的 天际线 可能不同。
我们被允许为 任意数量的建筑物 的高度增加 任意增量(不同建筑物的增量可能不同) 。 高度为 0 的建筑物的高度也可以增加。然而,增加的建筑物高度 不能影响 从任何主要方向观察城市得到的 天际线 。
在 不改变 从任何主要方向观测到的城市 天际线 的前提下,返回建筑物可以增加的 最大高度增量总和 。
示例 1:
输入:grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
输出:35
解释:建筑物的高度如上图中心所示。
用红色绘制从不同方向观看得到的天际线。
在不影响天际线的情况下,增加建筑物的高度:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
示例 2:
输入:grid = [[0,0,0],[0,0,0],[0,0,0]] 输出:0 解释:增加任何建筑物的高度都会导致天际线的变化。
提示:
n == grid.lengthn == grid[r].length2 <= n <= 500 <= grid[r][c] <= 100
解题思路
方法一:贪心
根据题目描述,我们可以将每个单元格 的值增加至第 行的最大值和第 列的最大值中的较小值,这样可以保证不影响天际线,即每个单元格增加的高度为 。
因此,我们可以先遍历一次矩阵,分别计算出每行和每列的最大值,记录在数组 和 中,然后再遍历一次矩阵,计算出答案即可。
时间复杂度 ,空间复杂度 。其中 为矩阵 的边长。
class Solution:
def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
row_max = [max(row) for row in grid]
col_max = [max(col) for col in zip(*grid)]
return sum(
min(row_max[i], col_max[j]) - x
for i, row in enumerate(grid)
for j, x in enumerate(row)
)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N^2) because we traverse the grid multiple times for maxima computation and increase aggregation. Space complexity is O(N) to store row and column maxima arrays. |
| 空间 | O(N) |
面试官常问的追问
外企场景- question_mark
Candidate first identifies row and column maxima as constraints.
- question_mark
Candidate applies a greedy approach per cell rather than attempting global optimization.
- question_mark
Candidate correctly sums increases without violating skyline invariants.
常见陷阱
外企场景- error
Forgetting to limit increase by both row and column maxima, changing the skyline.
- error
Attempting to sort or globally optimize instead of using greedy per cell.
- error
Miscomputing the total increase by using absolute heights rather than differences.
进阶变体
外企场景- arrow_right_alt
Allow decreasing building heights to minimize the skyline while maximizing the sum of reductions.
- arrow_right_alt
Solve for rectangular m x n grids instead of square n x n grids.
- arrow_right_alt
Consider non-uniform skyline constraints where only specific rows or columns are constrained.