leetcode 892. Surface Area of 3D Shapes ( Python )

538 阅读20分钟

描述

On a N * N grid, we place some 1 * 1 * 1 cubes.

Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).

Return the total surface area of the resulting shapes.

Example 1:

Input: [[2]]
Output: 10

Example 2:

Input: [[1,2],[3,4]]
Output: 34

Note:

1 <= N <= 50
0 <= grid[i][j] <= 50

解析

根据题意,这道题和之前的 883. Projection Area of 3D Shapes 这道题有点类似,但是思路不一样,这道题要先计算总的表面积,再减去 2 倍的重复部分的表面积即可,时间复杂度为 O(N^2),空间复杂度为 O(1)。

解答

class Solution(object):
    def surfaceArea(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        result = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j]: result += 4*grid[i][j]+2
                if i: result -= min(grid[i][j],grid[i-1][j])*2
                if j: result -= min(grid[i][j],grid[i][j-1])*2
        return result
                
                 	      
		

运行结果

Runtime: 68 ms, faster than 86.11% of Python online submissions for Surface Area of 3D Shapes.
Memory Usage: 11.8 MB, less than 56.25% of Python online submissions for Surface Area of 3D Shapes.

每日格言:生命不等于是呼吸,生命是活动。

请作者喝吃樱桃 支付宝

支付宝

微信

微信