其他分享
首页 > 其他分享> > 【LeetCode击败99%+】保持城市天际线

【LeetCode击败99%+】保持城市天际线

作者:互联网

题目

例子:

输入: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
输出: 35
解释: 
The grid is:
[ [3, 0, 8, 4], 
  [2, 4, 5, 7],
  [9, 2, 6, 3],
  [0, 3, 1, 0] ]

从数组竖直方向(即顶部,底部)看“天际线”是:[9, 4, 8, 7]
从水平水平方向(即左侧,右侧)看“天际线”是:[8, 7, 9, 3]

在不影响天际线的情况下对建筑物进行增高后,新数组如下:

gridNew = [ [8, 4, 8, 7],
            [7, 4, 7, 7],
            [9, 4, 8, 7],
            [3, 3, 3, 3] ]
说明:

1 < grid.length = grid[0].length <= 50。
 grid[i][j] 的高度范围是: [0, 100]。
一座建筑物占据一个grid[i][j]:换言之,它们是 1 x 1 x grid[i][j] 的长方体。

代码

class Solution {
    public int maxIncreaseKeepingSkyline(int[][] grid) {
        int[] rMax = new int[grid.length];
        int[] cMax = new int[grid.length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j]>rMax[i]) rMax[i] = grid[i][j];
                if (grid[i][j]>cMax[j]) cMax[j] = grid[i][j];
            }
        }

        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                count = count + Math.min(rMax[i], cMax[j]) - grid[i][j];
            }
        }
        return count;
    }
}

结果

用时内存
击败100.00%击败70.02%

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/max-increase-to-keep-city-skyline
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

标签:天际线,int,rMax,99%,length,grid,建筑物,LeetCode
来源: https://blog.csdn.net/weixin_44870909/article/details/110674369