73. Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
解法一
使用list存放0的位置,最后0所在位置对应的行和列都成为0。
public class Solution {
public void setZeroes(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return;
}
if (matrix[0] == null || matrix[0].length == 0) {
return;
}
List<List<Integer>> lists = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
lists.add(Arrays.asList(i, j));
}
}
}
for (List<Integer> list : lists) {
int i = list.get(0);
int j = list.get(1);
for (int c = 0; c < matrix[0].length; c++) {
matrix[i][c] = 0;
}
for (int r = 0; r < matrix.length; r++) {
matrix[r][j] = 0;
}
}
}
}
解法二
O(1)的空间复杂度
顶栏和左栏存放该栏的状态,如果某一位置为0,该位置的[i][0] = 0, [0][j] = 0;对于[i][0]元素的状态,用一个变量col0存储。
public class Solution {
public void setZeroes(int[][] matrix) {
int col0 = 1, rows = matrix.length, cols = matrix[0].length;
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) {
col0 = 0;
}
for (int j = 1; j < cols; j++)
if (matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 1; j--)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if (col0 == 0) {
matrix[i][0] = 0;
}
}
}
}