给定一个m * n的矩阵,如果一个元素为0,那么把这个元素所在的行和列都设置为0。我们可以借助两个boolean数组,一个代表行row,一个代表列col。遍历数组,如果遇到元素matrix[i][j]为0,就把相应的行row[i]设置为true; 相应的列col[j]设置为true。最后遍历这两个boolean数组,当遇到true时(row[i] == true || col[j] == true)就把当前元素设置为0。空间复杂度为O(m+n)。代码如下:
public class Solution { public void setZeroes(int[][] matrix) { if(matrix == null || matrix.length == 0) return; int m = matrix.length; int n = matrix[0].length; boolean[] row = new boolean[m]; boolean[] col = new boolean[n]; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) { if(matrix[i][j] == 0) { row[i] = true; col[j] = true; } } for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) { if(row[i] == true || col[j] == true) matrix[i][j] = 0; } } }
还有一种优化的方法可以把空间复杂度优化为O(1), 代码如下:
public class Solution { public void setZeroes(int[][] matrix) { if(matrix == null || matrix.length == 0) return; int m = matrix.length; int n = matrix[0].length; boolean row = false, col = false; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) { if(matrix[i][j] == 0) { if(i == 0) { row = true; } else if(j == 0){ col = true; } else { matrix[i][0] = 0; matrix[0][j] = 0; } } } for(int i = m - 1; i >= 0; i--) for(int j = n - 1; j >= 0; j--) { if(i == 0 && row == true || j == 0 && col == true || matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0; } } }