Skip to content

Commit 3a445f2

Browse files
committed
product of array except self solution
1 parent d7eaecb commit 3a445f2

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* ๋ฌธ์ œ: https://leetcode.com/problems/product-of-array-except-self/description/
3+
*
4+
* ์š”๊ตฌ์‚ฌํ•ญ:
5+
* nums: number[]๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ ์ž๊ธฐ์ž์‹ ์„ ์ œ์™ธํ•œ ๊ฐ’๋“ค์˜ ๊ณฑ์„ O(n)์œผ๋กœ ๋‚˜๋ˆ—์…ˆ ์—†์ด number[]๋กœ ๋ฆฌํ„ด
6+
*
7+
* * */
8+
9+
const productOfArrayExceptSelf = (nums) => {
10+
let answer = new Array(nums.length);
11+
// ๊ฐ€์žฅ ์™ผ์ชฝ์—๋Š” ์•„๋ฌด๊ฒƒ๋„ ์—†์œผ๋‹ˆ 1๋กœ ์‹œ์ž‘
12+
answer[0] = 1;
13+
14+
// ์™ผ์ชฝ์—์„œ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ๊ฐ€๋ฉด์„œ ๋ˆ„์  ๊ณฑ
15+
for(let i = 1; i < nums.length; i++) {
16+
answer[i] = answer[i - 1] * nums[i - 1];
17+
}
18+
19+
// ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ ๋์ด ์—†์œผ๋‹ˆ 1๋กœ ์‹œ์ž‘
20+
let right = 1;
21+
22+
// ์—ญ์ˆœํšŒ
23+
for(let i = nums.length -1; i >=0; i--) {
24+
answer[i] = answer[i] * right;
25+
26+
right = right * nums[i];
27+
}
28+
29+
return answer;
30+
}

0 commit comments

Comments
ย (0)