leecode [保持城市天际线]代码实现

题目描述  https://leetcode-cn.com/problems/max-increase-to-keep-city-skyline/description/

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

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

Python代码实现如下,如有错误遗漏,欢迎指正!

import pandas as pd
import numpy as np


def maxIncreaseKeepingSkyline( grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
nums = grid
nums = np.array(nums).T
top_bottom = []
for i in range(nums.shape[0]):
ls = []
for j in range(nums.shape[1]):
ls.append(nums[i][j])
top_bottom.append(max(ls))

left_right = []
for i in range(nums.shape[1]):
ms = []
for j in range(nums.shape[0]):
ms.append(nums[j][i])
left_right.append(max(ms))
a = [[0 for _ in range(len(left_right))] for _ in range(len(top_bottom))]
a = np.array(a).T
cnt = 0
for i in range(len(left_right)):
for j in range(len(top_bottom)):
aa = min(left_right[i], top_bottom[j])
cnt = cnt + aa - nums[i][j]
a[i][j] = aa
return cnt


if __name__ == '__main__':
grid = [[3, 0, 8, 4], [2, 4, 5, 7], [9, 2, 6, 3], [0, 3, 1, 0]]
res = maxIncreaseKeepingSkyline(grid=grid)
print(res)

猜你喜欢

转载自www.cnblogs.com/John-Geek-2018/p/9934851.html