Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
这道题最糟糕的算法是空间复杂度为O(mn),这里就不介绍这种解法了
下面的解法是定义两个boolean数组,然后出现0就把0的所在行和所在列置true,代码如下
public void setZeroes(int[][] matrix) {
boolean[] row = new boolean[matrix.length];
boolean[] col = new boolean[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] = true;
col[j] = true;
}
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (row[i] || col[j])
matrix[i][j] = 0;
}
}
}
其实这段代码比较简单,简而言之就2步,找0和置0
找0
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
row[i] = true;
col[j] = true;
}
}
}
置0
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (row[i] || col[j])
matrix[i][j] = 0;
}
}