-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
✅73.矩阵置零 #33
Labels
Comments
解题思路:
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function (matrix) {
let firstRowHasZero = false;
let firstColHasZero = false;
for (let i = 0; i < matrix.length; i++) {
if (matrix[i][0] === 0) {
firstColHasZero = true;
}
}
for (let i = 0; i < matrix[0].length; i++) {
if (matrix[0][i] === 0) {
firstRowHasZero = true;
}
}
for (let i = 1; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] === 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (let i = 1; i < matrix.length; i++) {
for (let j = 1; j < matrix[0].length; j++) {
if (matrix[i][0] === 0 || matrix[0][j] === 0) {
matrix[i][j] = 0;
}
}
}
if (firstColHasZero) {
for (let i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
if (firstRowHasZero) {
for (let i = 0; i < matrix[0].length; i++) {
matrix[0][i] = 0;
}
}
return matrix;
}; |
复杂度:O(m*n) /**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function(matrix) {
// O(n*m)
const row = new Set();
const column = new Set();
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] === 0) {
row.add(i);
column.add(j);
}
}
}
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
if (row.has(i) || column.has(j)) {
matrix[i][j] = 0;
}
}
}
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
73.矩阵置零
给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
示例 1:
示例 2:
The text was updated successfully, but these errors were encountered: