Skip to content

Commit 0cd8146

Browse files
committed
refactor: feat: 238. Product of Array Except Self
1 parent ce97cce commit 0cd8146

File tree

1 file changed

+11
-20
lines changed

1 file changed

+11
-20
lines changed

โ€Žproduct-of-array-except-self/gwbaik9717.jsโ€Ž

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,19 @@
66
* @return {number[]}
77
*/
88
var productExceptSelf = function (nums) {
9-
let count0 = 0;
9+
const n = nums.length;
10+
const fromLeft = Array.from({ length: n + 1 }, () => 1);
11+
const fromRight = Array.from({ length: n + 1 }, () => 1);
1012

11-
const totalProduct = nums.reduce((acc, num) => {
12-
if (num === 0) {
13-
count0++;
14-
}
13+
for (let i = 1; i <= n; i++) {
14+
fromLeft[i] = fromLeft[i - 1] * nums[i - 1];
15+
}
1516

16-
return acc * num;
17-
}, 1);
17+
for (let i = n - 1; i >= 0; i--) {
18+
fromRight[i] = fromRight[i + 1] * nums[i];
19+
}
1820

19-
return nums.map((num) => {
20-
if (num === 0) {
21-
// 0์ด 2 ๊ฐœ ์ด์ƒ ์กด์žฌํ•  ๋•Œ
22-
if (count0 > 1) {
23-
return 0;
24-
}
25-
26-
// 0์ด 1 ๊ฐœ ์กด์žฌํ•  ๋•Œ
27-
// 0์„ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ product ๊ณ„์‚ฐ (์ด ๊ณผ์ •์€ ๋‹จ ํ•œ๋ฒˆ๋งŒ ์กด์žฌํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” ์—ฌ์ „ํžˆ O(n))
28-
return nums.filter((num) => num !== 0).reduce((a, c) => a * c, 1);
29-
}
30-
31-
return totalProduct / num;
21+
return nums.map((num, i) => {
22+
return fromLeft[i] * fromRight[i + 1];
3223
});
3324
};

0 commit comments

Comments
ย (0)