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?
题意有点不太明确 实际上是需要先记录值为0的坐标 然后再更新 不然只要matrix有一个0 就全变成0了
话说100之内的题都好难啊。。。
0,0,1,1 0,0,0,0
1,1,1,1 0,0,1,1
1,1,1,1 ————> 0,0,1,1
1,1,1,1 0,0,1,1
void setZeroes(vector<vector<int> > &matrix) {
int col0 = 1, rows = matrix.size(), cols = matrix[0].size();
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) col0 = 0;
for (int j = 1; j < cols; j++)
if (matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 1; j--)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if (col0 == 0) matrix[i][0] = 0;
}
}
从左上到右下 用首行和首列记录值为0的元素 然后从右下到左上 更新
第一行,第一列因为是标识位 必须最后再更新