Skip to content

Commit fa5ed09

Browse files
committed
product of array except self colution
1 parent d6578e6 commit fa5ed09

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
var productExceptSelf = function (nums) {
6+
7+
const NUMS_LENGTH = nums.length;
8+
const isZeroArray = []; //boolean
9+
let zeroCount = 0;
10+
11+
let totalProduct = nums.reduce((acc, item) => {
12+
if (item === 0) {
13+
zeroCount++;
14+
isZeroArray.push(true);
15+
return acc;
16+
} else {
17+
isZeroArray.push(false);
18+
return acc * item;
19+
}
20+
}, 1);
21+
22+
// ์—ฃ์ง€ ์ผ€์ด์Šค ๋Œ€๋น„ 1: nums์˜ ์š”์†Œ ์ค‘ 0์ด ๋‘ ๊ฐœ ์ด์ƒ์ธ ๊ฒฝ์šฐ
23+
if (zeroCount >= 2) {
24+
totalProduct = 0;
25+
}
26+
27+
const tempArray = [];
28+
29+
for (let i = 0; i < NUMS_LENGTH; i++) {
30+
if (isZeroArray[i] === true) {
31+
tempArray.push(totalProduct);
32+
} else if (zeroCount >= 1) {
33+
// ์—ฃ์ง€ ์ผ€์ด์Šค ๋Œ€๋น„ 2: isZeroArray[i]๊ฐ€ false ๋”๋ผ๋„ nums์˜ ์š”์†Œ ์ค‘ zero๊ฐ€ ํ•˜๋‚˜๋ผ๋„ ์žˆ๋Š” ๊ฒฝ์šฐ
34+
// (์ง€๊ธˆ ๋ณด๋‹ˆ ์ด ๋ถ€๋ถ„์€ zeroCount === 1๋กœ ํ–ˆ์–ด๋„ ๋  ๊ฒƒ ๊ฐ™๋„ค์š”...)
35+
tempArray.push(0);
36+
} else {
37+
tempArray.push(totalProduct / nums[i]);
38+
}
39+
}
40+
41+
return tempArray;
42+
};
43+

0 commit comments

Comments
ย (0)