【LeetCode】73. Set Matrix Zeroes

时间:2023-03-09 13:33:51
【LeetCode】73. 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?

提示:

这题要求用常数的空间去解决,那么我们就可以利用第一行和第一列的元素去标记该行或该列是否在更新时要全部变成0。但是单纯这样操作会使得第一行和第一列的原始状态丢失。

因此,我们需要额外一个变量去保存第一列(或者第一行也可以)在更新时是否要变成0,这样就不会有问题了。

另外还有一个让代码更加精简的小窍门,就是在更新的时候从下往上(Bottom-Up),这样就不用担心会破坏第一行或第一列的数据了。

代码:

class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int height = matrix.size();
int width = height ? matrix[].size() : ;
if (!height || !width) {
return;
}
int col0 = ;
for (int i = ; i < height; ++i) {
if (matrix[i][] == ) {
col0 = ;
}
for (int j = ; j < width; ++j) {
if (matrix[i][j] == ) {
matrix[i][] = ;
matrix[][j] = ;
}
}
}
for (int i = height - ; i >= ; --i) {
for (int j = width - ; j >= 1; --j) {
if (matrix[i][] == || matrix[][j] == ) {
matrix[i][j] = ;
}
}
if (col0 == ) {
matrix[i][] = ;
}
}
}
};