Why my Java solution NOT accepted?


  • 0
    Y
    public class Solution {
    public void setZeroes(int[][] matrix) {
        for(int i=0; i<matrix.length; i++){
            for(int j=0; j<matrix[0].length; j++){
                if(matrix[i][j]==0){
                    matrix[i][0]=0;
                    matrix[0][j]=0;
                }
            }
        }
        for(int m=0; m<matrix.length; m++){
            for(int n=0; n<matrix[0].length; n++){
                if(matrix[m][0]==0||matrix[0][n]==0){    
                    matrix[m][n]=0;
                }
            }
        }
    }
    

    }


  • 0
    J

    It looks that we should mark the first row/col if it is zero, or the whole matrix will be set to Zero.

    test case: {{0,0,0,5},{4,3,1,4},{0,1,1,4},{1,2,1,3},{0,0,1,1}}

    for(int m=0; m<matrix.length; m++){
            for(int n=0; n<matrix[0].length; n++){
          //a. when m = 0, n = 3, since matrix[0][0] (matrix[m][0]) = 0, set matrix[0][3] to '0'
          //b. when m = 1, n = 0, since matrix[0][0] (matrix[0][n]) = 0, set matrix[1][0] to '0'
         //...
        // c. when m =1, n = 3, since matrix[1][0](matrix[m][0]) is '0', it will set matrix[1][3] to '0'
       // which is not right, and it is the consequence of b step
                if(matrix[m][0]==0||matrix[0][n]==0){     
                    matrix[m][n]=0; 
                }
            }
        }
    }
    

    Output: {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}

    Expected: [[0,0,0,0],[0,0,0,4],[0,0,0,0],[0,0,0,3],[0,0,0,0]]

    Solution: https://leetcode.com/discuss/73568/o-1-space-java-solution


Log in to reply
 

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