Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ]
Example 2:
Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ]
Follow up:
- 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?
给定一个矩阵,如果元素(i,j)是0,则把第i行和第j列都赋值为0。要求用常数空间。 因为前面的元素如果赋值为0,会影响后面的行列,所以是否赋值为0需要预先存起来,最后再一次性处理矩阵。 可以用一个行向量row[]和一个列向量col[]分别存储第i行和第j列是否应该赋值为0,具体方法就是扫描矩阵,如果matrix[i][j]==0,则赋值row[i]=0和col[j]=0表明第i行和第j列应该被赋值为0。但是这种方法需要O(m+n)的空间。
为了不使用额外的空间,我们可以借用原矩阵的第一行和第一列当作上面的row[]和col[],但是需要提前判断第一行和第一列是否应该被置为0。具体代码如下:
class Solution {
public:
void setZeroes(vector<vector<int> >& matrix)
{
int m = matrix.size();
if (m == 0)
return;
int n = matrix[0].size();
if (n == 0)
return;
bool clearFirstRow = false, clearFirstColumn = false;
for (int i = 0; i < m; ++i) { // first column
if (matrix[i][0] == 0) {
clearFirstColumn = true;
break;
}
}
for (int j = 0; j < n; ++j) { // first row
if (matrix[0][j] == 0) {
clearFirstRow = true;
break;
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
if (matrix[0][j] == 0 || matrix[i][0] == 0)
matrix[i][j] = 0;
}
}
if (clearFirstRow) {
for (int j = 0; j < n; ++j)
matrix[0][j] = 0;
}
if (clearFirstColumn) {
for (int i = 0; i < m; ++i)
matrix[i][0] = 0;
}
}
};
本代码提交AC,用时59MS。
Pingback: LeetCode Set Matrix Zeroes | nce3xin_code