The original title link is here: https://leetcode.com/problems/set-matrix-zeroes/
The original idea is to copy a matrix, scan the copied matrix, if you encounter 0, change the original matrix, so use O (m*n) space.
Observe whether a number should be changed to 0 to see if the same column is 0, so it can be optimized to use only two Boolean array, one to record all rows, one to record all columns 0, so use O (m+n) space.
The better way is to use the first row and the first column instead of the two record array above the amount, then the first row and the first column should be changed to 0, in fact, only need two Boolean value:firstrow, Firstcol to record the good, so only need to use O (1) Space.
Time complexity is always O (m*n).
AC Java:
1 Public classSolution {2 Public voidSetzeroes (int[] matrix) {3 if(Matrix = =NULL|| Matrix.length = = 0 | | Matrix[0].length = = 0){4 return;5 }6 //Record If first row, first Columna contains 07 BooleanFirstRow =false;8 BooleanFirstcol =false;9 for(inti = 0; i<matrix.length; i++){Ten if(matrix[i][0] = = 0){ OneFirstcol =true; A Break; - } - } the for(intj = 0; j<matrix[0].length; J + +){ - if(Matrix[0][j] = = 0){ -FirstRow =true; - Break; + } - } + A //For the rest of the matrix, if there is 0, mark its corresponding row and Columna as 0 at first column and first row at for(inti = 1; i<matrix.length; i++){ - for(intj = 1; j<matrix[0].length;j++){ - if(Matrix[i][j] = = 0){ -Matrix[i][0] = 0; -MATRIX[0][J] = 0; - } in } - } to + //Scan The matrix for the second time, if corresponding mark was 0, change this element to 0 - for(inti = 1; i<matrix.length; i++){ the for(intj = 1; j<matrix[0].length; J + +){ * if(matrix[i][0] = = 0 | | matrix[0][j] = = 0){ $MATRIX[I][J] = 0;Panax Notoginseng } - } the } + A //Change first row and Columna at last the if(firstrow) { + for(intj = 0; j<matrix[0].length; J + +){ -MATRIX[0][J] = 0; $ } $ } - if(firstcol) { - for(inti = 0; i<matrix.length; i++){ theMatrix[i][0] = 0; - }Wuyi } the } -}
Leetcode Set Matrix Zeroes