1.使用两个变量,记录「首行 & 首列」是否该被置零
2.「非首行首列」的位置
- 将置零信息存储到原矩阵
- 根据置零信息,置零「非首行首列」的位置
3.根据变量 ,置零「首行 & 首列」
class Solution {
public void setZeroes(int[][] matrix) {
int rowLen = matrix.length, colLen = matrix[0].length;
Boolean rowZero = false, colZero = false;
for (int r = 0; r < rowLen && !rowZero; r++) if (matrix[r][0] == 0) rowZero = true;
for (int c = 0; c < colLen && !colZero; c++) if (matrix[0][c] == 0) colZero = true;
for (int r = 1; r < rowLen; r++) {
for (int c = 1; c < colLen; c++) {
if(matrix[r][c] == 0) matrix[r][0] = matrix[0][c] = 0;
}
}
for (int c = 1; c < colLen; c++) {
for (int r = 1; r < rowLen && matrix[0][c] == 0; r++) {
matrix[r][c] = 0;
}
}
for (int r = 1; r < rowLen; r++) {
if (matrix[r][0] == 0) Arrays.fill(matrix[r], 0);
}
if (rowZero) for (int r = 0; r < rowLen; r++) matrix[r][0] = 0;
if (colZero) Arrays.fill(matrix[0], 0);
}
}