Skip to content

Commit 949e83e

Browse files
committed
solve product of array except self
1 parent 9b5f555 commit 949e83e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
var productExceptSelf = function (nums) {
6+
let answer = [];
7+
8+
const p = [];
9+
for (let i = 0; i < nums.length; i++) {
10+
if (i == 0) {
11+
const n = nums.slice(i + 1).reduce((acc, curr) => (acc *= curr), 1);
12+
console.log(n);
13+
p.push([1, n]);
14+
answer.push(1 * n);
15+
} else {
16+
const [left, right] = p[i - 1];
17+
if (nums[i] === 0) {
18+
const n = nums.slice(i + 1).reduce((acc, curr) => (acc *= curr), 1);
19+
p.push([left * nums[i - 1], n]);
20+
answer.push(left * nums[i - 1] * n);
21+
} else {
22+
p.push([left * nums[i - 1], right / nums[i]]);
23+
answer.push((left * nums[i - 1] * right) / nums[i]);
24+
}
25+
}
26+
}
27+
28+
return answer;
29+
};

0 commit comments

Comments
 (0)