Java O(row) Space Solution


  • 0
    Z

    It's easy to understand with just two temp array space. And if you choose the fewer between rows and cols, it's much better, but the code would be longer.

    class Solution {
        public int[][] imageSmoother(int[][] M) {
            int row = M.length, col = M[0].length;
            int[] temp1 = new int[row];
            int[] temp2 = new int[row];
          
            for(int i = 0; i < row; i++){
                temp1[i] = findAve(M, i, 0);
            }
            
            
            
            for(int j = 1; j < col; j++){
                for(int i = 0; i < row; i++)
                    temp2[i] = findAve(M, i, j);
                for(int i = 0; i < row; i++){
                    M[i][j-1]=temp1[i];
                    temp1[i] = temp2[i];
                }
            }
            
            for( int i = 0; i < row; i++)
                M[i][col-1] = temp1[i];
            return M;
        }
        
        public int findAve(int [][] M, int i, int j){
            int sum = 0, num = 9;
            for(int a = i-1; a <= i+1; a++){
                for(int b = j-1; b<=j+1; b++){
                    if((a<0 || a> M.length-1) || (b<0 || b>M[0].length-1)){
                        num--;
                    }else{
                        sum+=M[a][b];
                    }
                }
            }
            return sum/num;
        }
            
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.