73. Set Matrix Zeroes
Given a \(m \times n\) matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
Follow up:
\(\bullet\)A straight forward solution using O(mn) space is probably a bad idea.
\(\bullet\)A simple improvement uses O(m + n) space, but still not the best solution.
\(\bullet\)Could you devise a constant space solution?
思路:
1.若某一个数为0,则将这一行的第一个数以及这一列的第一个数设为0作为标记位。值得注意的是,如果第一列某个数为0,则这一行和第一列的数都要变为0,所以要单独设置一个标志位col0。
2.检查行时自底向上,检查列时自右向左。注意检查列时只能检查到第二列,否则会重复变0。最后检查col0是否为0,若为0,则将第一列变为0。
Solution:
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) {
for (int i = 0; i < rows; i++) {
matrix[i][0] = 0;
}
}
}
性能:
Runtime: 44 ms Memory Usage: 11.5 MB