Skip to content

Commit ce97cce

Browse files
committed
feat: 238. Product of Array Except Self
1 parent 79f948b commit ce97cce

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time complexity: O(n)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* @param {number[]} nums
6+
* @return {number[]}
7+
*/
8+
var productExceptSelf = function (nums) {
9+
let count0 = 0;
10+
11+
const totalProduct = nums.reduce((acc, num) => {
12+
if (num === 0) {
13+
count0++;
14+
}
15+
16+
return acc * num;
17+
}, 1);
18+
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;
32+
});
33+
};

0 commit comments

Comments
ย (0)