Skip to content

Commit 2a6d8a6

Browse files
committed
Feat: 73. Set Matrix Zeroes
1 parent 1fe8c7d commit 2a6d8a6

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

set-matrix-zeroes/HC-kang.ts

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/**
2+
* https://leetcode.com/problems/set-matrix-zeroes
3+
* T.C. O(r * c)
4+
* S.C. O(r + c)
5+
*/
6+
function setZeroes(matrix: number[][]): void {
7+
const r = matrix.length;
8+
const c = matrix[0].length;
9+
10+
const zeroRows = new Set<number>();
11+
const zeroCols = new Set<number>();
12+
13+
for (let i = 0; i < r; i++) {
14+
for (let j = 0; j < c; j++) {
15+
if (matrix[i][j] === 0) {
16+
zeroRows.add(i);
17+
zeroCols.add(j);
18+
}
19+
}
20+
}
21+
22+
for (let i = 0; i < r; i++) {
23+
for (let j = 0; j < c; j++) {
24+
if (zeroRows.has(i) || zeroCols.has(j)) {
25+
matrix[i][j] = 0;
26+
}
27+
}
28+
}
29+
}
30+
31+
/**
32+
* T.C. O(r * c)
33+
* S.C. O(1)
34+
*/
35+
function setZeroes(matrix: number[][]): void {
36+
const r = matrix.length;
37+
const c = matrix[0].length;
38+
39+
let firstRowHasZero = false;
40+
let firstColHasZero = false;
41+
42+
if (matrix[0].some((val) => val === 0)) {
43+
firstRowHasZero = true;
44+
}
45+
46+
if (matrix.some((row) => row[0] === 0)) {
47+
firstColHasZero = true;
48+
}
49+
50+
for (let i = 1; i < r; i++) {
51+
for (let j = 1; j < c; j++) {
52+
if (matrix[i][j] === 0) {
53+
matrix[i][0] = 0;
54+
matrix[0][j] = 0;
55+
}
56+
}
57+
}
58+
59+
for (let i = 1; i < r; i++) {
60+
if (matrix[i][0] === 0) {
61+
matrix[i].fill(0);
62+
}
63+
}
64+
65+
for (let j = 1; j < c; j++) {
66+
if (matrix[0][j] === 0) {
67+
matrix.forEach((row) => (row[j] = 0));
68+
}
69+
}
70+
71+
if (firstRowHasZero) {
72+
matrix[0].fill(0);
73+
}
74+
75+
if (firstColHasZero) {
76+
matrix.forEach((row) => (row[0] = 0));
77+
}
78+
}

0 commit comments

Comments
 (0)