leetcode (Surface Area of 3D Shapes)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85690617

Title: Surface Area of 3D Shapes    892

Difficulty:Easy

原题leetcode地址:  https://leetcode.com/problems/surface-area-of-3d-shapes/

1.  见代码注释

时间复杂度:O(n^2),嵌套for循环,最长长度为n*n。

空间复杂度:O(1),没有申请额外空间。

    /**
     * 1、先计数每一个的表面积的和 num * 4 + 2
     * 2、删除重叠的部分,重叠部分就是相邻较小的乘以2
     * @param grid
     * @return
     */
    public static int surfaceArea(int[][] grid) {

        int count = 0;

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] > 0) {
                    count += grid[i][j] * 4 + 2;
                }
                if (i > 0) {
                    count -= Math.min(grid[i][j], grid[i - 1][j]) * 2;
                }
                if (j > 0) {
                    count -= Math.min(grid[i][j], grid[i][j - 1]) * 2;
                }
            }
        }

        return count;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/85690617