Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. click to show follow up. Follow up: Did you use extra space? A straight forward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space solution?
一次过,空间复杂度为O(m+n), 下一次做的时候寻找constant space solution。用boolean array也可以,用bit vector可能会更节省.
其实还可以再优化,我们考虑使用第一行和第一列来记录上面所说的行和列的置0情况,这里问题是那么第一行和第一列自己怎么办?想要记录它们自己是否要置0,只需要两个变量(一个是第一行,一个是第一列)就可以了。然后就是第一行和第一列,如果要置0,就把它的值赋成0(反正它最终也该是0,无论第一行或者第一列有没有0),否则保留原值。然后根据第一行和第一列的记录对其他元素进行置0。最后再根据前面的两个标记来确定是不是要把第一行和第一列置0就可以了。这样的做法只需要两个额外变量,所以空间复杂度是O(1)。
时间上来说上面方法都是一样的,需要进行两次扫描,一次确定行列置0情况,一次对矩阵进行实际的置0操作,所以总的时间复杂度是O(m*n)。
O(1)space,just two variables
1 public class Solution { 2 public void setZeroes(int[][] matrix) { 3 if (matrix==null || matrix.length==0 || matrix[0].length==0) return; 4 boolean fstRow = false; 5 boolean fstCol = false; 6 for (int i=0; i<matrix.length; i++) { 7 for (int j=0; j<matrix[0].length; j++) { 8 if (i == 0 && matrix[i][j] == 0) fstRow = true; 9 if (j == 0 && matrix[i][j] == 0) fstCol = true; 10 if (matrix[i][j] == 0) { 11 matrix[i][0] = 0; 12 matrix[0][j] = 0; 13 } 14 } 15 } 16 for (int i=1; i<matrix.length; i++) { 17 for (int j=1; j<matrix[0].length; j++) { 18 if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0; 19 } 20 } 21 if (fstRow) { 22 for (int j=0; j<matrix[0].length; j++) { 23 matrix[0][j] = 0; 24 } 25 } 26 if (fstCol) { 27 for (int i=0; i<matrix.length; i++) { 28 matrix[i][0] = 0; 29 } 30 } 31 } 32 }