Solution 1
我好像对这种合理利用空间的问题都不是很擅长……,之前的原位哈希问题我就没想好,这个也是……
官方题解的思路就是使用矩阵的第一行和第一列记录当前位置是否需要归零,但是这样就会丢掉第一行和第一列原始的状态,那就用两个额外的状态量计算好了。
- 时间复杂度: O ( M N ) O(MN) O(MN) ,其中 M M M 和 N N N 分别为数组的尺寸,所有元素遍历两次(检查和置零)
- 空间复杂度: O ( 1 ) O(1) O(1) ,按照要求原位处理
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
bool zeroFirstRow = false;
bool zeroFirstCol = false;
for (int i = 0; i < matrix.size(); ++i) {
if (matrix[i][0] == 0) {
zeroFirstCol = true;
break;
}
}
for (int i = 0; i < matrix[0].size(); ++i) {
if (matrix[0][i] == 0) {
zeroFirstRow = true;
break;
}
}
for (int i = 1; i < matrix.size(); ++i) {
for (int j = 1; j < matrix[0].size(); ++j) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < matrix.size(); ++i) {
for (int j = 1; j < matrix[0].size(); ++j) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
if (zeroFirstRow) {
for (int i = 0; i < matrix[0].size(); ++i) {
matrix[0][i] = 0;
}
}
if (zeroFirstCol) {
for (int i = 0; i < matrix.size(); ++i) {
matrix[i][0] = 0;
}
}
}
};
Solution 2
Solution 1的Python实现
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
zeroFirstRow, zeroFirstCol = False, False
for i in range(len(matrix)):
if matrix[i][0] == 0:
zeroFirstCol = True
break
for i in range(len(matrix[0])):
if matrix[0][i] == 0:
zeroFirstRow = True
break
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i][j] == 0:
matrix[i][0] = 0;
matrix[0][j] = 0;
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0;
if zeroFirstRow:
for i in range(len(matrix[0])):
matrix[0][i] = 0
if zeroFirstCol:
for i in range(len(matrix)):
matrix[i][0] = 0