可以选择遍历两遍matrix
,一遍记录哪些行哪些列需要置0,一遍置0
O(1)空间复杂度的做法:
首先设置两个boolean
型变量记录第0行和第0列是否需要置0
然后用第0行和第0列记录需要置0的行和列
java
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
boolean row0 = false, col0 = false;
for (int j = 0; j < n; j++) {
if (matrix[0][j] == 0) row0 = true;
}
for (int i = 0; i < m; i++) {
if (matrix[i][0] == 0) col0 = true;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] == 0) matrix[0][j] = matrix[i][0] = 0;
}
}
// set 0
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;
}
}
if (row0) {
for (int j = 0; j < n; j++) {
matrix[0][j] = 0;
}
}
if (col0) {
for (int i = 0; i < m; i++) {
matrix[i][0] = 0;
}
}
}
}