73. Matrix zeroing
Given an mxn matrix, if an element is 0 , set all elements in its row and column to 0. Please use the in-place algorithm.
Example 1:
输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]
Example 2:
输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
hint:
- m == matrix.length
- n == matrix[0].length
- 1 <= m, n <= 200
- -2^31 <= matrix[i][j] <= 2^31 - 1
Answer ideas:
- Scan the elements of the two-dimensional array. If the scanned element is 0, record the row and set all rows to 0.
- And use a column array to count which column should be set to 0
- Finally, scan the column array and set the columns that need to be set to 0.
class Solution {
// 原地换0 数字范围是int的范围
public void setZeroes(int[][] matrix) {
int[] n = new int[matrix[0].length]; // TODO 额外的空间
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0; // TODO 将当前行标记为已置为1
n[j] = 1; // TODO 将当列标记为已置为1
}
}
if (matrix[i][0] == 0) {
int index = 0;
while (index < matrix[i].length) {
// 先把统计 后把行替换为0 避免替换覆盖掉其他覆盖掉其他的列的替换细节
matrix[i][index++] = 0;
}
}
}
for (int i = 0; i < n.length; i++) {
if (n[i] == 1) {
int index = 0;
while (index < matrix.length) {
// 最后列替换为0
matrix[index++][i] = 0;
}
}
}
}
}