Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

练习题10:城市天际线 #21

Open
chenhuiYj opened this issue Jul 17, 2020 · 0 comments
Open

练习题10:城市天际线 #21

chenhuiYj opened this issue Jul 17, 2020 · 0 comments

Comments

@chenhuiYj
Copy link
Owner

在二维数组grid中,grid[i][j]代表位于某处的建筑物的高度。 我们被允许增加任何数量(不同建筑物的数量可能不同)的建筑物的高度。 高度 0 也被认为是建筑物。

最后,从新数组的所有四个方向(即顶部,底部,左侧和右侧)观看的“天际线”必须与原始数组的天际线相同。 城市的天际线是从远处观看时,由所有建筑物形成的矩形的外部轮廓。 请看下面的例子。

建筑物高度可以增加的最大总和是多少?

例子:
输入: 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] ]

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

思路

1.首先遍历grid,计算出水平([8, 7, 9, 3])与垂直([9, 4, 8, 7])的天际线。

2.然后根据得出的水平与垂直天际线,计算出每一项可以得到的最高数值

var maxIncreaseKeepingSkyline = function(grid) {
    var vertical=[]
    var horizontal=[]
    var result=[]
    var sum=0
    var sumNew=0
    for(let i=0;i<grid.length;i++){
        horizontal.push(Math.max.apply(null,grid[i]))
        vertical[i]=0
        for(let j=0;j<grid.length;j++){
            sum+=grid[j][i]
            vertical[i]=grid[j][i]>vertical[i]?grid[j][i]:vertical[i]
        }
    }
    for(let i=0;i<horizontal.length;i++){
        result.push([])
        for(let j=0;j<vertical.length;j++){
            result[i].push(Math.min.call(null,horizontal[i],vertical[j]))
            sumNew+=Math.min.call(null,horizontal[i],vertical[j])
        }
    }
    return sumNew-sum
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant