- 题目描述:
编写一种算法,若 M × N 矩阵中某个元素为 0,则将其所在的行与列清零。
- 力扣官方题解
- ChatGPT
遍历整个矩阵,记录所有为 0 的元素的行号和列号。
根据记录的行号和列号,将对应的行与列清零。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| function setZeroes(matrix) { const m = matrix.length; const n = matrix[0].length;
const zeroRows = new Set(); const zeroCols = new Set();
for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (matrix[i][j] === 0) { zeroRows.add(i); zeroCols.add(j); } } }
for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (zeroRows.has(i) || zeroCols.has(j)) { matrix[i][j] = 0; } } } }
const matrix = [ [1, 1, 1], [1, 0, 1], [1, 1, 1], ];
setZeroes(matrix); console.log(matrix);
|
- 我的解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| var setZeroes = function (matrix) { let row = []; let column = []; for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { if (0 === matrix[i][j]) { if (!row.includes(i)) { row.push(i); } if (!column.includes(j)) { column.push(j); } } } }
if (row.length === 0 && column.length === 0) { return matrix; } else { row.forEach((row) => { for (let i = 0; i < matrix[row].length; i++) { matrix[row][i] = 0; } }); column.forEach((column) => { for (let i = 0; i < matrix.length; i++) { matrix[i][column] = 0; } }); } };
const matrix1 = [ [1, 1, 1], [1, 0, 1], [1, 1, 1], ]; setZeroes(matrix1); console.log(matrix1);
|