Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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)
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
if(matrix.empty() || matrix[].empty())
return; int m = matrix.size();
int n = matrix[].size(); vector<bool> row(m, false);
vector<bool> col(n, false); for(int i = ; i < m; i ++)
{
for(int j = ; j < n; j ++)
{
if(matrix[i][j] == )
{
row[i] = true;
col[j] = true;
}
}
} for(int i = ; i < m; i ++)
{
for(int j = ; j < n; j ++)
{
if(row[i] == true)
matrix[i][j] = ;
if(col[j] == true)
matrix[i][j] = ;
}
}
}
};
解法二:
使用第一行和第一列记录该行和该列是否应该置零。
对于由此覆盖掉的原本信息,只要单独遍历第一行第一列判断是否需要置零即可。
空间复杂度O(1)
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
if(matrix.empty() || matrix[].empty())
return;
int m = matrix.size();
int n = matrix[].size();
bool col0 = false;
bool row0 = false;
for(int i = ; i < m; i ++)
{
if(matrix[i][] == )
{
col0 = true;
break;
}
}
for(int j = ; j < n; j ++)
{
if(matrix[][j] == )
{
row0 = true;
break;
}
}
for(int i = ; i < m; i ++)
{
for(int j = ; j < n; j ++)
{
if(matrix[i][j] == )
{
matrix[][j] = ;
matrix[i][] = ;
}
}
}
for(int i = ; i < m; i ++)
{
if(matrix[i][] == )
{
for(int j = ; j < n; j ++)
{
matrix[i][j] = ;
}
}
}
for(int j = ; j < n; j ++)
{
if(matrix[][j] == )
{
for(int i = ; i < m; i ++)
{
matrix[i][j] = ;
}
}
}
if(col0 == true)
{
for(int i = ; i < m; i ++)
{
matrix[i][] = ;
}
}
if(row0 == true)
{
for(int j = ; j < n; j ++)
{
matrix[][j] = ;
}
}
}
};