题目描述:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Example
Given a matrix
[
[1,2],
[0,3]
],
return
[
[0,2],
[0,0]
]
Challenge
题目思路:
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?
题目要求用constant space去解,那么就想到了把zero的信息写在matrix中。如果(i,j)的位置上位0,那么就意味着i行j列都为0。这里我会把(i,0)和(0, j)的位置标记为0,这表示i行都为0,j列都为0。需要注意的是(0,0)这个位置是分不清行和列的,所以我增加了两个bool:zero_row和zero_col,以此来区别(0,0)为0的时候到底是表示0行为0还是0列为0. 标记完了以后,就可以填0了。这里要注意的是,0行和0列要放在最后overwrite,不然有用的信息会被覆盖掉。
Mycode(AC = 44ms):
class Solution {
public:
/**
* @param matrix: A list of lists of integers
* @return: Void
*/
void setZeroes(vector<vector<int> > &matrix) {
// write your code here
int num_rows = matrix.size();
if (num_rows == 0) return;
int num_cols = matrix[0].size();
// if (i, j) is zero, then use first row and
// first column to record the zero
bool zero_row = false, zero_col = false;
for (int i = 0; i < num_rows; i++) {
for (int j = 0; j < num_cols; j++) {
if (matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
zero_row = zero_row || (i == 0);
zero_col = zero_col || (j == 0);
}
}
}
// zero-out all the columns except first column
for (int j = 1; j < num_cols; j++) {
if (matrix[0][j] == 0) {
for (int i = 1; i < num_rows; i++) {
matrix[i][j] = 0;
}
}
}
// zero-out all the rows except first row
for (int i = 1; i < num_rows; i++) {
if (matrix[i][0] == 0) {
for (int j = 1; j < num_cols; j++) {
matrix[i][j] = 0;
}
}
}
// zero-out the first row if needed
if (zero_row) {
for (int i = 0; i < num_cols; i++) {
matrix[0][i] = 0;
}
}
// zero-out the first column if needed
if (zero_col) {
for (int i = 0; i < num_rows; i++) {
matrix[i][0] = 0;
}
}
}
};