Given 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?
Subscribe to see which companies asked this question
1 Public classSolution {2 Public voidSetzeroes (int[] matrix) {3 if(Matrix = =NULL|| Matrix.length = = 0 | | Matrix[0].length = = 0)return;4 intm = matrix.length, n = matrix[0].length;5 int[] Rowflag =New int[m];6 int[] Colflag =New int[n];7 for(inti = 0; I < m; i++){8 for(intj = 0; J < N; J + +){9 if(Matrix[i][j] = = 0){TenRowflag[i] = 1; OneCOLFLAG[J] = 1; A } - } - } the for(inti = 0; I < m; i++){ - if(Rowflag[i] = = 1){ - for(intj = 0; J < N; J + +){ -MATRIX[I][J] = 0; + } - } + } A for(inti = 0; I < n; i++){ at if(Colflag[i] = = 1){ - for(intj = 0; J < M; J + +){ -Matrix[j][i] = 0; - } - } - } in } -}
Set Matrix Zeroes Java Solutions