Description
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Solution
代码1:空间O(m + n),62 ms AC
将矩阵的0的状态存储在行列两个数组中
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix)
{
int m = matrix.size(), n = matrix[0].size();
vector<int> row(m);
vector<int> col(n);
for(int i=0;i<m;i++)
row[i] = 0;
for(int j=0;j<n;j++)
col[j] = 0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(matrix[i][j] == 0)
{
row[i] = 1;
col[j] = 1;
}
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(row[i]==1 || col[j]==1)
matrix[i][j] = 0;
}
}
}
};
代码2:空间O(1),52 ms AC
将矩阵的0的状态存储在矩阵的第一行和第一列中,然后第一行第一列另外单独判断
class Solution {
public:
int row = 1, col = 1; //判断第一行、第一列是否为0
void setZeroes(vector<vector<int>>& matrix)
{
int m = matrix.size(), n = matrix[0].size();
for(int i=0;i<m;i++)
if(matrix[i][0] == 0)
col = 0;
for(int j=0;j<n;j++)
if(matrix[0][j] == 0)
row = 0;
for(int i=1;i<m;i++)
{
for(int j=1;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[i][0]==0 || matrix[0][j]==0)
matrix[i][j] = 0;
}
}
//最后处理第一行和第一列
if(row == 0)
for(int j=0;j<n;j++)
matrix[0][j] = 0;
if(col == 0)
for(int i=0;i<m;i++)
matrix[i][0] = 0;
}
};