leetcode (Image Smoother)

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

Title:Image Smoother    661

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/image-smoother/

1.  注意有些数的周围没有8个数(3个或者5个的)

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

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

    /**
     * 注意有些数的周围没有8个数
     * @param M
     * @return
     */
    public static int[][] imageSmoother(int[][] M) {

        if (M == null) {
            return M;
        }
        int row = M.length;
        if (row == 0) {
            return new int[0][];
        }
        int column = M[0].length;

        int result[][] = new int[row][column];

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                result[i][j] = average(M, i, j, row, column);
            }
        }

        return result;

    }

    private static int average(int[][] M, int i, int j, int row, int column) {

        int sum = M[i][j];
        int count = 1;

        if (i - 1 >= 0 && j - 1 >= 0) {
            sum += M[i - 1][j - 1];
            count++;
        }
        if (i - 1 >= 0) {
            sum += M[i - 1][j];
            count++;
        }
        if (i - 1 >= 0 && j + 1 < column) {
            sum += M[i - 1][j + 1];
            count++;
        }
        if (j - 1 >= 0) {
            sum += M[i][j - 1];
            count++;
        }
        if (j + 1 < column) {
            sum += M[i][j + 1];
            count++;
        }
        if (i + 1 < row && j - 1 >= 0) {
            sum += M[i + 1][j - 1];
            count++;
        }
        if (i + 1 < row) {
            sum += M[i + 1][j];
            count++;
        }
        if (i + 1 < row && j + 1 < column) {
            sum += M[i + 1][j + 1];
            count++;
        }

        return sum / count;
    }


 

猜你喜欢

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