解题思路
首先找到四个主要方向(东南西北)的天际线情况。南北看是一样的,东西看也是一样的。所以统计出每行的最值,每列的最值,用一个n的数组存储。分别存储行和列的最值。最值的位置进行标记,然后对于其余未标记的元素,可以增量的最值为min(max[row],max[col])。
C++
class Solution {
public:int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {int n = grid.size();vector<int> rows(n);vector<int> cols(n);for (int i = 0; i < n; i++){// 遍历行rows[i] = *max_element(grid[i].begin(), grid[i].end());int temp = 0;for (int j = 0; j < n; j++){if (grid[j][i] > temp) temp = grid[j][i];}cols[i] = temp;}int res = 0;for (int i = 0; i < n; i++){for (int j = 0; j < n; j++){int cmp = min(rows[i], cols[j]);if (grid[i][j] < cmp) res += cmp - grid[i][j];}}return res;}
};
java
class Solution {public int maxIncreaseKeepingSkyline(int[][] grid) {int n = grid.length;int[] rowMax = new int[n];int[] colMax = new int[n];for (int i = 0; i < n; 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 < n; i++){for (int j = 0; j < n; j++){res += Math.min(rowMax[i], colMax[j]) - grid[i][j];}}return res;}
}