题目描述
一座n x n的矩阵,每个元素代表该位置的高度。
城市的天际线指从上下左右观察矩阵,直视图的外边轮廓,就是城市的天际线。如下图:
允许为每个位置添加材料,但是要保证上下左右的天际线不变。求为所有位置加完材料后,加的总材料数。
解题思路
1、每个位置的天际线,左右看是同一行最高的元素,上下看是同一列最高的元素。 2、两个数组,记录每行和每列的最大高度。 3、依次遍历每个位置,计算行最高元素和列最高元素较小的那一个,和当前元素的差值。
java代码
class Solution {
public int maxIncreaseKeepingSkyline(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[] rowMax = new int[m];
int[] colMax = new int[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
rowMax[i] = Math.max(rowMax[i], grid[i][j]);
colMax[j] = Math.max(colMax[j], grid[i][j]);
}
}
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res += Math.min(rowMax[i], colMax[j]) - grid[i][j];
}
}
return res;
}
}
复杂度
时间复杂度:遍历矩阵两次,O(n^2) 空间复杂度:需要两个长度为n的数组记录行最大值和列最大值,O(n)
是否有更优解?
求大家评论区讨论