Skip to content

Commit 2200f1d

Browse files
committed
solve productExceptSelf
1 parent ff9dafd commit 2200f1d

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// answer[i] -> nums[i] ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€์˜ ๊ณฑ
2+
function productExceptSelf(nums: number[]): number[] {
3+
let left = [];
4+
let right = [];
5+
let acc = 1;
6+
7+
for (let i = 0; i < nums.length; i++) {
8+
left[i] = acc; // ์ด์ „๊ฒฐ๊ณผ๊นŒ์ง€์˜ ๋ˆ„์ ๊ฐ’์„ i๋ฒˆ์งธ์— ์ €์žฅ
9+
acc = acc * nums[i]; // ๋‹ค์Œ ์ €์žฅ์„ ์œ„ํ•ด ์—…๋ฐ์ดํŠธ
10+
}
11+
12+
acc = 1;
13+
for (let i = nums.length - 1; i >= 0; i--) {
14+
right[i] = acc;
15+
acc = acc * nums[i];
16+
}
17+
18+
let answer = [];
19+
for (let i = 0; i < nums.length; i++) {
20+
answer.push(left[i] * right[i]);
21+
}
22+
23+
return answer;
24+
}
25+
26+
// 2๋ฒˆ์งธ ์‹œ๋„
27+
// ๊ณต๊ฐ„๋ณต์žก๋„๋ฅผ O(1)๋กœ ์ค„์ผ ์ˆ˜ ์žˆ์„๊นŒ?
28+
// answer[i] -> nums[i] ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€์˜ ๊ณฑ
29+
function productExceptSelf(nums: number[]): number[] {
30+
let answer = [];
31+
let acc = 1;
32+
33+
for (let i = 0; i < nums.length; i++) {
34+
answer[i] = acc; // ์ด์ „๊ฒฐ๊ณผ๊นŒ์ง€์˜ ๋ˆ„์ ๊ฐ’์„ i๋ฒˆ์งธ์— ์ €์žฅ
35+
acc = acc * nums[i]; // ๋‹ค์Œ ์ €์žฅ์„ ์œ„ํ•ด ์—…๋ฐ์ดํŠธ
36+
}
37+
38+
acc = 1;
39+
for (let i = nums.length - 1; i >= 0; i--) {
40+
answer[i] = answer[i] * acc;
41+
acc = acc * nums[i];
42+
}
43+
44+
return answer;
45+
}

0 commit comments

Comments
ย (0)