Skip to content

Commit a49e7c9

Browse files
feat: product-of-array-except-self ํ’€์ด
1 parent a3da5a1 commit a49e7c9

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
var productExceptSelf = function(nums) {
2+
const n = nums.length;
3+
const left = new Array(n).fill(1);
4+
const right = new Array(n).fill(1);
5+
const answer = new Array(n).fill(1);
6+
7+
// ์˜ค๋ฅธ์ชฝ ๋ˆ„์ ๊ณฑ
8+
for (let i = n - 2; i >= 0; i--) {
9+
right[i] = right[i + 1] * nums[i + 1];
10+
}
11+
12+
// ์™ผ์ชฝ ๋ˆ„์ ๊ณฑ
13+
for (let i = 1; i < n; i++) {
14+
left[i] = left[i - 1] * nums[i - 1];
15+
}
16+
17+
// ์ตœ์ข… ๊ณฑ์…ˆ
18+
for (let i = 0; i < n; i++) {
19+
answer[i] = left[i] * right[i];
20+
}
21+
22+
return answer;
23+
};
24+
};
25+
//์‹œ๊ฐ„๋ณต์žก๋„ O(n)
26+
//๊ณต๊ฐ„๋ณต์žก๋„ O(n)
27+
// ์–ด๋ ค์› ๋˜ ์ : ํ•œ๋ฒˆ ํ’€์—ˆ๋˜ ๋ฌธ์ œ์ง€๋งŒ, ์ธ๋ฑ์Šค ๋ฒ”์œ„๋ฅผ ์„ค์ •ํ•˜๋Š” ์ ์—์„œ ์–ด๋ ค์›€์„ ๊ฒช์—‡๋‹ค.
28+
29+
30+
//์—ฌ๊ธฐ์„œ ๊ณต๊ฐ„๋ณต์žก๋„๋ฅผ O(1)๋กœ ์ตœ์ ํ™” ํ•  ์ˆ˜ ์žˆ๋‹ค. ( ๋ฆฌํ„ด ๋ฐฐ์—ด ์ œ์™ธ)
31+
/**
32+
* ๋ฌธ์ œ ๋‚ด์—์„œ Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
33+
*/
34+
var productExceptSelf = function(nums) {
35+
const n = nums.length;
36+
const answer = new Array(n).fill(1);
37+
38+
// ์™ผ์ชฝ ๊ณฑ
39+
for (let i = 1; i < n; i++) {
40+
answer[i] = answer[i - 1] * nums[i - 1];
41+
}
42+
43+
// ์˜ค๋ฅธ์ชฝ ๊ณฑ ๋ˆ„์ ํ•˜๋ฉด์„œ answer์— ๊ณฑํ•ด์คŒ
44+
let right = 1;
45+
for (let i = n - 1; i >= 0; i--) {
46+
answer[i] *= right;
47+
right *= nums[i];
48+
}
49+
50+
return answer;
51+
};

0 commit comments

Comments
ย (0)