Skip to content

Commit 68e598d

Browse files
committed
feat(soobing): week2 > product-of-array-except-self
1 parent 53ce7c7 commit 68e598d

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 문제 유형
3+
* - Array
4+
*
5+
* 문제 설명
6+
* - 자기 자신을 제외한 나머지의 곱 구하기
7+
*
8+
* 아이디어
9+
* 1) Array - 자기 자신보다 이전, 이후 의 누적곱(left, right) 구하고, 최종적으로 곱하기
10+
* 2) 0읠 제외한 나머지의 곱, 0의 갯수 카운트를 이용하여 조건에 따라 계산하기
11+
*/
12+
function productExceptSelf(nums: number[]): number[] {
13+
const answer = Array(nums.length).fill(0);
14+
let zeroCount = 0;
15+
const productWithoutZero = nums.reduce((acc, cur) => {
16+
if (cur === 0) {
17+
zeroCount++;
18+
return acc;
19+
}
20+
return cur * acc;
21+
}, 1);
22+
23+
for (let i = 0; i < nums.length; i++) {
24+
if (zeroCount > 0) {
25+
if (nums[i]) answer[i] = 0;
26+
else answer[i] = zeroCount > 1 ? 0 : productWithoutZero;
27+
} else {
28+
answer[i] = productWithoutZero / nums[i];
29+
}
30+
}
31+
return answer;
32+
}
33+
34+
function productExceptSelfArrayVersion(nums: number[]): number[] {
35+
const answer = Array(nums.length);
36+
const left = Array(nums.length).fill(1);
37+
const right = Array(nums.length).fill(1);
38+
39+
for (let i = 1; i < nums.length; i++) {
40+
left[i] = left[i - 1] * nums[i - 1];
41+
}
42+
43+
for (let i = nums.length - 2; i >= 0; i--) {
44+
right[i] = right[i + 1] * nums[i + 1];
45+
}
46+
47+
for (let i = 0; i < nums.length; i++) {
48+
answer[i] = left[i] * right[i];
49+
}
50+
51+
return answer;
52+
}

0 commit comments

Comments
 (0)