Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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.
提示的算法很容易就想到。constant space的算法, 自己一开始总是想找出一种操作,然后遍历一遍解决。
其实最简单的方法就是直接在matrix上记录行、列是否0的信息。这里的技巧在于,选择了在第一行和第一列上记录,用0值表示这一行(或列)为0。因为只要这一行(或列)为0,最终这个值也是要设为0的,不会影响最终的结果。如果在第一行的元素在该列没有0,那么他是否要设为0就取决于第一行是否有0. 第一列的元素同理。
1 class Solution { 2 public: 3 void setZeroes(vector<vector<int> > &matrix) { 4 int row = matrix.size(); 5 if (row == 0) return; 6 int col = matrix[0].size(); 7 if (col == 0) return; 8 9 bool firstRowZero = false, firstColZero = false; 10 for (int i = 0; i < col; ++i) { 11 if (matrix[0][i] == 0) { 12 firstRowZero = true; 13 break; 14 } 15 } 16 17 for (int i = 0; i < row; ++i) { 18 if (matrix[i][0] == 0) { 19 firstColZero = true; 20 break; 21 } 22 } 23 24 for (int i = 1; i < row; ++i) { 25 for (int j = 1; j < col; ++j) { 26 if (matrix[i][j] == 0) { 27 matrix[i][0] = 0; 28 matrix[0][j] = 0; 29 } 30 } 31 } 32 33 for (int i = 1; i < row; ++i) { 34 for (int j = 1; j < col; ++j) { 35 if (matrix[i][0] == 0 || matrix[0][j] == 0) { 36 matrix[i][j] = 0; 37 } 38 } 39 } 40 41 if (firstRowZero) { 42 for (int i = 0; i < col; ++i) { 43 matrix[0][i] = 0; 44 } 45 } 46 47 if (firstColZero) { 48 for (int i = 0; i < row; ++i) { 49 matrix[i][0] = 0; 50 } 51 } 52 } 53 };