Skip to content

Commit a2d9e6a

Browse files
committed
product of array except self μ™„λ£Œ
- time complexitiy: O(n) - space complexitiy: O(1)
1 parent 756d0ea commit a2d9e6a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/* -------------------------------------------------------------------------- */
2+
/* time complexitiy: O(n), space complexitiy: O(n) */
3+
/* -------------------------------------------------------------------------- */
4+
5+
// const productExceptSelf = function (nums) {
6+
// const result = [];
7+
// const n = nums.length;
8+
9+
// if (n < 2) return result;
10+
11+
// const left = [1];
12+
// const right = [1];
13+
14+
// for (let i = 1; i < n; i++) {
15+
// left[i] = left[i - 1] * nums[i - 1];
16+
// }
17+
18+
// for (let i = 1; i < n; i++) {
19+
// right[i] = right[i - 1] * nums[n - i];
20+
// }
21+
22+
// for (let i = 0; i < n; i++) {
23+
// result[i] = left[i] * right[n - 1 - i];
24+
// if (result[i] === 0) result[i] = Math.abs(result[i]); //0이 -0으둜 ν‘œμ‹œλ˜λŠ” 이슈 ν•Έλ“€
25+
// }
26+
27+
// return result;
28+
// };
29+
30+
/* -------------------------------------------------------------------------- */
31+
/* time complexitiy: O(n), space complexitiy: O(1) */
32+
/* -------------------------------------------------------------------------- */
33+
34+
const productExceptSelf = function (nums) {
35+
const result = [1];
36+
const n = nums.length;
37+
38+
if (n < 2) return result;
39+
40+
let prefix = 1;
41+
let postfix = 1;
42+
43+
for (let i = 1; i < n; i++) {
44+
prefix *= nums[i - 1];
45+
result[i] = prefix;
46+
if (i === n - 1 && result[i] === 0) result[i] = Math.abs(result[i]); //0이 -0으둜 ν‘œμ‹œλ˜λŠ” 이슈 ν•Έλ“€
47+
}
48+
49+
for (let i = n - 2; i >= 0; i--) {
50+
postfix *= nums[i + 1];
51+
result[i] *= postfix;
52+
if (result[i] === 0) result[i] = Math.abs(result[i]); //0이 -0으둜 ν‘œμ‹œλ˜λŠ” 이슈 ν•Έλ“€
53+
}
54+
55+
return result;
56+
};

0 commit comments

Comments
Β (0)