Skip to content

Commit f71a743

Browse files
committed
solve(w02): 238. Product of Array Except Self
1 parent 5ce8df8 commit f71a743

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
* 시간 복잡도: O(n)
3+
* 공간 복잡도: O(n)
4+
*/
5+
6+
/**
7+
* @param {number[]} nums
8+
* @return {number[]}
9+
*/
10+
11+
var productExceptSelf = function(nums) {
12+
const lefts = nums.reduce((products, num, i) => {
13+
products.push(i === 0 ? 1 : products[i - 1] * nums[i - 1]);
14+
return products;
15+
}, []
16+
);
17+
18+
return nums.reduceRight((result, num, i) => {
19+
const rights = i === nums.length - 1 ? 1 : result.rightProduct * nums[i + 1];
20+
result.products[i] *= rights;
21+
result.rightProduct = rights;
22+
return result;
23+
}, { products: lefts, rights: 1 }
24+
).products;
25+
};

0 commit comments

Comments
 (0)