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?
Given a m*n matrix, if an element is 0, then the row and column of this element are changed to 0, requiring a space complexity of O (1).
1, the practice of violence is to set up a similar matrix, each encounter 0, and then the second matrix corresponding position 0, the space complexity of O (MN).
2, then a slight optimization is the time each encounter 0, the record needs to set 0 of the line number and column number, the space complexity of O (m+n).
3, if the space complexity is required to 1, in fact, only need to record the method in 2, recorded in the first row and the first column on the line.
Public classSolution { Public voidSetzeroes (int[] matrix) { if(Matrix.length = = 0) return ; intLen1 = matrix.length, len2 = matrix[0].length; BooleanRow0 =false, col0 =false; for(inti = 0;i<len1;i++){ if(matrix[i][0] = = 0) {col0=true; Break; } } for(inti = 0;i<len2;i++){ if(Matrix[0][i] = = 0) {row0=true; Break; } } for(inti = 0;i<len1;i++){ for(intj = 0;j<len2;j++){ if(Matrix[i][j] = = 0) {matrix[i][0] = 0; matrix[0][J] = 0; } } } for(inti = 1;i<len1;i++){ if(matrix[i][0] = = 0) for(intj = 1;j<len2;j++) Matrix[i][j]= 0; } for(inti = 1;i<len2;i++){ if(Matrix[0][i] = = 0) for(intj = 1;j<len1;j++) Matrix[j][i]= 0; } if(row0) for(inti = 0;i<len2;i++) matrix[0][i] = 0; if(col0) for(inti = 0;i<len1;i++) matrix[i][0] = 0; return ; }}
Leetcode Set Matrix Zeroes-----java