Constraints: m == matrix.length n == matrix[0].length 1 <= m, n <= 200 -231 <= matrix[i][j] <= 231 - 1
Follow up: A straightforward 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?
矩阵置零。
给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。
classSolution { publicvoidsetZeroes(int[][] matrix) { // corner case if (matrix == null || matrix.length == 0) { return; }
// normal case intm= matrix.length; intn= matrix[0].length; booleanrow=false; booleancol=false; // mark if first row and first col has zero for (inti=0; i < m; i++) { for (intj=0; j < n; j++) { if (matrix[i][j] == 0) { matrix[i][0] = matrix[0][j] = 0; if (i == 0) row = true; if (j == 0) col = true; } } }
// change the inner part to zeroes based on the first row and first col for (inti=1; i < m; i++) { if (matrix[i][0] == 0) { for (intj=1; j < n; j++) { matrix[i][j] = 0; } } } for (intj=1; j < n; j++) { if (matrix[0][j] == 0) { for (inti=1; i < m; i++) { matrix[i][j] = 0; } } }
// change the first row and first col if needed if (row) { for (intj=0; j < n; j++) { matrix[0][j] = 0; } } if (col) { for (inti=0; i < m; i++) { matrix[i][0] = 0; } } } }
/** * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ var setZeroes = function (matrix) { // corner case if (matrix.length === 0 || matrix === null) return;
// normal case let m = matrix.length let n = matrix[0].length; let rowZero = false; let colZero = false; // check if first row has zero for (let i = 0; i < m; i++) { if (matrix[i][0] === 0) colZero = true; }
// check if first column has zero for (let i = 0; i < n; i++) { if (matrix[0][i] === 0) rowZero = true; }
// scan all the other rows and columns for (let i = 1; i < m; i++) { for (let j = 1; j < n; j++) { if (matrix[i][j] === 0) { matrix[0][j] = 0; matrix[i][0] = 0; } } }
// scan again to see if we should mark the whole row or column to be zero for (let i = 1; i < m; i++) { for (let j = 1; j < n; j++) { if (matrix[i][0] === 0 || matrix[0][j] === 0) { matrix[i][j] = 0; } } }
// check if we should mark the first row and first column to be zero if (rowZero) { for (let i = 0; i < n; i++) matrix[0][i] = 0; } if (colZero) { for (let i = 0; i < m; i++) matrix[i][0] = 0; } };