Topic:
Iven a m x n Matrix, if an element was 0, set its entire row and column to 0. Do it on place.
Click to show follow up.
Follow up:
Did you use extra space?
A straight forward solution using O (mn) space is probably a bad idea.
A Simple Improvement uses O (m + n) space, but still is not the best solution.
Could you devise a constant space solution?
test instructions and analysis: if the element of a matrix is 0, then its row and column are set to 0, can not use the spatial complexity of O (1)
code One : Traverse the matrix with two sets to record the rows and columns that need to change, and then in the traversal settings, the spatial complexity is 0 (m+ns)
1 classSolution {2 Public voidSetzeroes (int[] matrix) {3 introw =matrix.length;4 if(row==0)return;5 intCol = matrix[0].length;6 7Set<integer> RowSet =NewHashset<>();8Set<integer> Colset =NewHashset<>();9 Ten for(inti=0;i<row;i++){ One for(intj=0;j<col;j++){ A if(matrix[i][j]==0){ - Rowset.add (i); - Colset.add (j); the } - } - } - + //Line -Iterator<integer> Iterator =rowset.iterator (); + while(Iterator.hasnext ()) { AInteger res =Iterator.next (); at for(inti=0;i<col;i++){ -Matrix[res][i] = 0; - } - } - -iterator =colset.iterator (); in while(Iterator.hasnext ()) { -Integer res =Iterator.next (); to for(inti=0;i<row;i++){ +Matrix[i][res] = 0; - } the } * } $}
Code two: the method of not using extra space is similar, that is, the first row and the first column are marked. First determine whether the first row of a line contains 0 and is recorded with two bool variables. In this way, all the rows and columns are reflected in the first row and the first column after iterating over them. The next step is to place the row and column 0, excluding the first row and the first column, based on the first row and 0 elements of the first column.
1 classSolution {2 Public voidSetzeroes (int[] matrix) {3 introw =matrix.length;4 if(row==0)return;;5 intCol = matrix[0].length;6 BooleanFR =false, FC =false;7 for(inti=0;i<row;i++){8 for(intj=0;j<col;j++){9 if(matrix[i][j]==0){Ten if(i = = 0) FR =true; One if(j = = 0) FC =true; AMatrix[0][j]=0; -Matrix[i][0]=0; - } the } - } - //based on the first row and 0 elements of the first column, place the row and column 0, excluding the first row and the first column. - for(inti=1;i<row;i++) { + for(intj = 1; J < Col; J + +) { - if(matrix[i][0] = = 0 | | matrix[0][j] = = 0) { +MATRIX[I][J] = 0; A } at } - } - - - //Finally, if the first row has or the first column has a 0 element, set to 0 - if(FR) { in for(inti=0;i<col;i++){ -Matrix[0][i] = 0; to } + } - if(FC) { the for(inti = 0; i < row; i++) { *Matrix[i][0] = 0; $ }Panax Notoginseng } - } the}
[Leetcode] 73. Set Matrix Zeroes Java