Skip to content

Commit 1682c3f

Browse files
authored
product-of-array-except-self
1 parent 3b62824 commit 1682c3f

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
function productExceptSelf(nums: number[]): number[] {
2+
// 시간 복잡도: O(n), 공간 복잡도: O(1)
3+
const n = nums.length;
4+
const answer = new Array(n).fill(1);
5+
6+
// answer[i]에 left 곱 저장
7+
for (let i = 1; i < n; i++) {
8+
answer[i] = answer[i - 1] * nums[i - 1];
9+
}
10+
11+
// right 곱을 한 변수에 저장하면서 answer에 곱하기
12+
let rightProduct = 1;
13+
for (let i = n - 1; i >= 0; i--) {
14+
answer[i] *= rightProduct;
15+
rightProduct *= nums[i];
16+
}
17+
18+
return answer;
19+
}

0 commit comments

Comments
 (0)