73-setZeroes.js
2.39 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes2 = function (matrix) {
let m = matrix.length;
let n = matrix[0].length;
let rs = []
// copy init matrix
for (let i = 0; i < m; i++) {
let r = []
// for(let j=0;j<n;j++) {
// r.push(void 0)
// }
rs.push(r);
}
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
let v = matrix[i][j]
if (v === 0) {
for (let x = 0; x < n; x++) {
rs[i][x] = 0;
}
for (let y = 0; y < m; y++) {
rs[y][j] = 0;
}
} else {
(rs[i][j] === void 0) && (rs[i][j] = v);
}
}
}
return rs;
};
var setZeroes_ok = function (matrix) {
let m = matrix.length;
let n = matrix[0].length;
let rs = [];
// init matrix
for (let i = 0; i < m; i++) {
rs.push([]);
}
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
let v = matrix[i][j]
if (v === 0 && rs[i][j] === void 0) {
for (let x = 0; x < n; x++) {
let t = matrix[i][x];
if (t !== 0) {
rs[i][x] = t;
}
matrix[i][x] = 0;
}
for (let y = 0; y < m; y++) {
let t = matrix[y][j];
if (t !== 0) {
rs[y][j] = t;
}
matrix[y][j] = 0;
}
} else {
rs[i][j] = v;
}
}
}
};
var setZeroes = function (matrix) {
let m = matrix.length;
let n = matrix[0].length;
let rows = new Set();
let cols = new Set();
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
let v = matrix[i][j]
if (v === 0) {
rows.add(i);
cols.add(j);
}
}
}
rows.forEach(e => {
for (let j=0;j<n;j++) {
matrix[e][j] = 0;
}
});
cols.forEach(e => {
for (let i=0;i<m;i++) {
matrix[i][e] = 0;
}
});
};
var matrix = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]];
setZeroes(matrix);
console.info(matrix);