Skip to content

Commit 6945bd0

Browse files
author
bhan
committed
product of array except self solution
1 parent 7e9affb commit 6945bd0

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
var productExceptSelf = function (nums) {
6+
// 1.
7+
// ๊ฐ ์ธ๋ฑ์Šค์—์„œ ์ž๊ธฐ ์ž์‹  ์ œ์™ธํ•œ ๋ฐฐ์—ด ๋งŒ๋“  ๋’ค ๊ณฑ์…ˆ ์ˆ˜ํ–‰ โ†’ ์‹œ๊ฐ„๋ณต์žก๋„ O(nยฒ)
8+
// (์ค‘์ฒฉ ๋ฃจํ”„๋กœ ์ธํ•ด ์‹œ๊ฐ„๋ณต์žก๋„ O(nยฒ), ํฐ ์ž…๋ ฅ์—์„œ๋Š” ์‹œ๊ฐ„ ์ดˆ๊ณผ ๋ฐœ์ƒ)
9+
let result = [];
10+
for (let i = 0; i < nums.length; i++) {
11+
const productNums = [...nums.slice(0, i), ...nums.slice(i + 1)];
12+
13+
let product = 1;
14+
for (let j = 0; j < productNums.length; j++) {
15+
product *= productNums[j];
16+
}
17+
result.push(product);
18+
}
19+
return result;
20+
21+
// 2.
22+
const n = nums.length;
23+
// ์ •๋‹ต ๋ฐฐ์—ด์„ 1๋กœ ์ดˆ๊ธฐํ™” (๊ณฑ์…ˆ์— ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š๋„๋ก)
24+
const answer = new Array(n).fill(1);
25+
26+
// ์™ผ์ชฝ ๋ˆ„์  ๊ณฑ ๊ณ„์‚ฐ
27+
let left = 1;
28+
for (let i = 0; i < n; i++) {
29+
answer[i] = left;
30+
left *= nums[i];
31+
}
32+
33+
// ์˜ค๋ฅธ์ชฝ ๋ˆ„์  ๊ณฑ ๊ณ„์‚ฐ
34+
let right = 1;
35+
for (let i = n - 1; i >= 0; i--) {
36+
answer[i] *= right;
37+
right *= nums[i];
38+
}
39+
40+
return answer;
41+
};

0 commit comments

Comments
ย (0)