Skip to content

Commit b2282f5

Browse files
committed
add solution : 238. Product of Array Except Self
1 parent 7bc8735 commit b2282f5

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
*
3+
* 접근 방법 :
4+
* - O(n)으로 풀어야 하니까 중첩이 아닌 배열 개별로 2번 순회 방법으로 접근
5+
* - 왼쪽 곱(prefixProduct)과 오른쪽 곱((suffixProduct)을 따로 계산해서 결과값에 저장
6+
*
7+
* 시간복잡도 : O(n)
8+
* - 배열 길이만큼 순회하니까 O(n)
9+
*
10+
* 공간복잡도 : O(n)
11+
* - 배열 길이만큼 결과값 저장하니까 O(n)
12+
*
13+
*/
14+
15+
function productExceptSelf(nums: number[]): number[] {
16+
let result: number[] = Array(nums.length).fill(1);
17+
let prefixProduct = 1;
18+
let suffixProduct = 1;
19+
20+
for (let i = 0; i < nums.length; i++) {
21+
result[i] = prefixProduct;
22+
prefixProduct *= nums[i];
23+
}
24+
25+
for (let i = nums.length - 1; i >= 0; i--) {
26+
result[i] *= suffixProduct;
27+
suffixProduct *= nums[i];
28+
}
29+
30+
return result;
31+
}

0 commit comments

Comments
 (0)