题目
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?
解析
题目很简单,关键是需要空间尽量小,我使用了两个vector来保存行和列的有0的点。
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
vector<int> colum;
vector<int> row;
for (int i = 0;i<matrix.size();i++)
{
bool flag = false;
for (int j = 0;j<matrix[0].size();j++)
{
if (matrix[i][j] == 0)
{
row.push_back(j);
flag = true;
}
}
if (flag)
colum.push_back(i);
}
for (int i = 0;i< colum.size();i++)
for (int j = 0;j<matrix[0].size();j++)
matrix[colum[i]][j] = 0;
for (int i = 0;i< matrix.size();i++)
for (int j = 0;j<row.size();j++)
matrix[i][row[j]] = 0;
}
};
不过空间复杂度还是高了,看大神代码吧,其实思路也很简单,就是把第一行和第一列作为其他行列是否有0的记录,有的话就把第一行或者列相应位置也改成0 。最后再把除第一行和第一列以外的可以相应去赋为0,不过这个时候已经没有了第一行列是否有0 的记录了,所以要在一开始就做记录。
void setZeroes(vector<vector<int> > &matrix)
{
const size_t m = matrix.size();
const size_t n = matrix[0].size();
bool row_has_zero = false; // 第一行是否存在0
bool col_has_zero = false; // 第一列是否存在0
for (size_t i = 0; i < n; i++)
if (matrix[0][i] == 0)
{
row_has_zero = true;
break;
}
for (size_t i = 0; i < m; i++)
if (matrix[i][0] == 0)
{
col_has_zero = true;
break;
}
for (size_t i = 1; i < m; i++)
for (size_t j = 1; j < n; j++)
if (matrix[i][j] == 0)
{
matrix[0][j] = 0;
matrix[i][0] = 0;
}
for (size_t i = 1; i < m; i++)
for (size_t j = 1; j < n; j++)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if (row_has_zero)
for (size_t i = 0; i < n; i++)
matrix[0][i] = 0;
if (col_has_zero)
for (size_t i = 0; i < m; i++)
matrix[i][0] = 0;
}