1. 程式人生 > >leetcode (Surface Area of 3D Shapes)

leetcode (Surface Area of 3D Shapes)

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;

    }