Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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 not the best solution.
Could you devise a constant space solution?
思路:先根据矩阵中的值记录下需要修改的行号和列号,然后对矩阵进行修改
public class Solution {
public void setZeroes(int[][] matrix) {
int [] row = new int[matrix.length];
int [] col = new int[matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length;j++) {
if (matrix[i][j] == 0) {
row[i] = 1;
col[j] = 1;
}
}
}
for (int i = 0; i < matrix.length; i++) {
if( row[i] == 1) {
for (int j = 0; j < matrix[0].length;j++)
matrix[i][j] = 0;
}
}
for (int i = 0; i < matrix[0].length; i++) {
if( col[i] == 1) {
for (int j = 0; j < matrix.length;j++)
matrix[j][i] = 0;
}
}
}
}