这里提供两种方法,第一种空间复杂度O(m + n).
通过两个一维数组,分别记录出现零的行号和列号,
在第二遍扫描的时候将相应的行和零都置零
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
int rows = matrix.size();
if(rows == 0)
return;
int cols = matrix[0].size();
vector<int> rowLabel(rows, 0);
vector<int> colLabel(cols, 0);
int rowCount = 0;
int colCount;
for(int i = 0; i < rows; i++)
{
colCount = 0;
for(int j = 0; j < cols; j++)
{
if(matrix[i][j] == 0)
{
rowLabel[i] = 1;
colLabel[j] = 1;
}
colCount++;
}
rowCount++;
}
for(int i = 0; i < rows; i++)
{
if(rowLabel[i] == 1)
{
for(int j = 0; j < cols; j++)
{
matrix[i][j] = 0;
}
}
}
for(int j = 0; j < cols; j++)
{
if(colLabel[j] == 1)
{
for(int i = 0; i < rows; i++)
{
matrix[i][j] = 0;
}
}
}
}
};
在这里注意到一个事实,就是扫描的方向是从左到右,从上到下的,
当扫描到当前位置时,改变它左上方的值是不会对接下来的扫描造成影响的,
因此可以用第一行,和第一列来代替上面的两个一维数组。
不过注意在二次扫描幅值时一定不要先处理第一行和第一列,若改变了它们
的值则无疑会产生错误