Skip to content

Commit b2fe6b4

Browse files
committed
solution Product of Array Except Self (#239)
#239
1 parent f30344e commit b2fe6b4

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
*
3+
* 풀이 1
4+
*
5+
* 아래와 같이 문제를 푸니, 성능적으로 문제가 발생했다.
6+
* 시간복잡도는 0(n2) / 공간 복잡도는 0(n)
7+
*
8+
* function productExceptSelf(nums: number[]): number[] {
9+
* if(nums.every(num => num === 0)) return nums; 시간 복잡도 0(n)
10+
* if(nums.length > 2 && nums.filter(num=> num ===0).length > 1) return new Array(nums.length).fill(0) 시간 복잡도 0(n) 공간 복잡도 0(n)
11+
* let result = [] 공간 복잡도 0(n)
12+
* for(let i =0;i<nums.length; i++){ 시간 복잡도 0(n)
13+
* let multi = 1;
14+
* const a= nums.filter((num,index)=> index !== i); 시간 복잡도 0(n) 공간 복잡도 0(n)
15+
* for(let item of a){ 시간 복잡도 0(n)
16+
* multi *= item
17+
* }
18+
* result.push(multi)
19+
* }
20+
* return result
21+
* };
22+
*
23+
* 풀이 2 는 누적합 알고리즘을 사용해서 왼쪽 방향에서 시작해 오른쪽 방향으로 곱하는 방식으로 문제 해결
24+
*
25+
*/
26+
27+
function productExceptSelf(nums: number[]): number[] {
28+
const n = nums.length;
29+
const result = new Array(n).fill(1);
30+
31+
let leftProduct = 1;
32+
for (let i = 0; i < n; i++) {
33+
result[i] *= leftProduct;
34+
leftProduct *= nums[i];
35+
}
36+
37+
let rightProduct = 1;
38+
for (let i = n - 1; i >= 0; i--) {
39+
result[i] *= rightProduct;
40+
rightProduct *= nums[i];
41+
}
42+
43+
return result;
44+
}

0 commit comments

Comments
 (0)