
核心思想:贪心,位置i,j上的建筑能够增加到的最大高度为当前行i上最高的建筑h1,和当前列j上最高的建筑h2去一个min即可,这样就可以不会影响边际线。
打卡代码:
class Solution {
public:int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {int n = grid[0].size();int N = 55;int res = 0;int col[N], row[N];// 求每一行的最大值for(int i = 0; i < n; i ++){int curmax = -1;for(int j = 0; j < n; j ++){if(grid[i][j] > curmax)curmax = grid[i][j];}row[i] = curmax;} // 求每一列的最大值for(int i = 0; i < n; i ++){int curmax = -1;for(int j = 0; j < n; j ++){if(grid[j][i] > curmax)curmax = grid[j][i];}col[i] = curmax;}// 根据col和row索引出答案for(int i = 0; i < n; i ++){for(int j = 0; j < n; j ++){int t = 0; // 当前位置需要增加的高度int curh = min(row[i], col[j]);// cout << curh << " ";t = curh - grid[i][j];res += t;}}return res;}
};
优化一下求解每行/列求最大值的代码:
class Solution { public:int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {int n = grid[0].size();int N = 55;int res = 0;vector<int> col(n), row(n);// 求每一行的最大值.求每一列的最大值for(int i = 0; i < n; i ++){for(int j = 0; j < n; j ++){row[i] = max(row[i], grid[i][j]);col[j] = max(col[j], grid[i][j]);}} // 根据col和row索引出答案for(int i = 0; i < n; i ++){for(int j = 0; j < n; j ++){int t = 0; // 当前位置需要增加的高度int curh = min(row[i], col[j]);t = curh - grid[i][j];res += t;}}return res;} };
