Very Clean Solution in Java


  • 10
    S

    Here we have a check function to check the boundary and a inner double loop to traverse the 9 potential candidates:

    public class ImageSmoother {
    
        public int[][] imageSmoother(int[][] M) {
            if (M == null) return null;
            int rows = M.length;
            if (rows == 0) return new int[0][];
            int cols = M[0].length;
    
            int result[][] = new int[rows][cols];
    
            for (int row = 0; row < rows; row++) {
                for (int col = 0; col < cols; col++) {
                    int count = 0;
                    int sum = 0;
                    for (int incR : new int[]{-1, 0, 1}) {
                        for (int incC : new int[]{-1, 0, 1}) {
                            if (isValid(row + incR, col + incC, rows, cols)) {
                                count++;
                                sum += M[row + incR][col + incC];
                            }
                        }
                    }
                    result[row][col] = sum / count;
                }
            }
    
            return result;
    
        }
    
        private boolean isValid(int x, int y, int rows, int cols) {
            return x >= 0 && x < rows && y >= 0 && y < cols;
        }
    }
    

  • 0
    N

    The time consumption is 76ms in my case, longer than 98% of other submissions. Wonder what the cause is.


  • 0
    N

    Similar approach. All we have to do here is add all possible cells around a given point.Let's say the give is (x,y) then the possible cells around it will be the following:

      (x-1,y-1)| (x-1,y) |(x-1,y+1)
      (x, y-1) |  {x,y}  |(x-1,y+1)
      (x+1,y-1)| (x+1,y) |(x+1,y+1)
    

    Runtime ~40 ms

    public int[][] imageSmoother(int[][] M) {
            int row = M.length, col = M[0].length;       
            int[][] result = new int[row][col];            
            for(int i=0;i<row;++i){ 
                for(int j=0;j<col;++j){      
                    int total = 0, points = 0;
                         for(int k=i-1;k<i+2;++k){ 
                             if(k>-1 && k<row){
                                 for(int l=j-1;l<j+2;++l){      
                                      if (l>-1 && l<col){
                                          total+=M[k][l];        
                                          ++points;
                                      }
                                  }
                             }
                         }
                    result[i][j] = (int) Math.floor(total/(double)points);
                }
            }
            
            return result;
        }

Log in to reply
 

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