Skip to content

Commit e569877

Browse files
author
jinvicky
committed
product of array except self arrsolution
1 parent 0ac068a commit e569877

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// prefix sum ํŒจํ„ด์„ ์‚ฌ์šฉํ•œ๋‹ค.
2+
// nums.length ๊ธธ์ด์˜ ์ •๋‹ต ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ  left, right ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•œ๋‹ค.
3+
// ์ฒ˜์Œ๋ถ€ํ„ฐ for๋ฌธ์œผ๋กœ nums๋งŒ ๋ˆ„์ ํ•ฉ ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ  ํ•ด๊ฒฐํ•˜๋ ค๊ณ  ํ–ˆ๋˜ ๊ฒŒ ์‹คํŒจ ์›์ธ์ด์—ˆ๋‹ค. ๋ณ€์ˆ˜ ์‚ฌ์šฉ ๋ฐ ๊ณ„์‚ฐ์‹์„ ๊ณ ๋ คํ•˜์ง€ ๋ชปํ•จ.
4+
class Solution {
5+
public int[] productExceptSelf(int[] nums) {
6+
int[] output = new int[nums.length];
7+
for (int i = 0; i < nums.length; i++) {
8+
output[i] = 1;
9+
}
10+
11+
// ์ •๋‹ต์— ๊ฐ’์„ ์ ์šฉํ•˜๊ณ  left, right์„ ์—…๋ฐ์ดํŠธํ•œ๋‹ค๋Š” ์ ์ด ์ค‘์š”ํ–ˆ๋‹ค. -> ์„ ์ ์šฉ ํ›„์—…๋ฐ์ดํŠธ๋ฅผ ์ž˜๋ชป ์ดํ•ดํ•ด์„œ ํ—ค๋งธ๋‹ค.
12+
int left = 1;
13+
for (int i = 0; i < nums.length; i++) {
14+
output[i] *= left; // 1,2,2,6
15+
left *= nums[i]; // 1,2,6,24 (output ์ ์šฉ์ด ๋๋‚ฌ์œผ๋ฏ€๋กœ 24๋Š” ์‚ฌ์‹ค์ƒ ์ ์šฉ๋˜์ง€ ์•Š๋Š”๋‹ค)
16+
}
17+
18+
int right = 1;
19+
for (int i = nums.length - 1; i >= 0; i--) {
20+
output[i] *= right; // 6,8,12,24 -> ๋ฐฐ์—ด ์ธ๋ฑ์Šค๊ฐ€ ์—ญ์ˆœ์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฒฐ๊ณผ์ ์œผ๋กœ [24, 12, 8, 6] ์ด ๋œ๋‹ค.
21+
right *= nums[i]; //
22+
}
23+
return output;
24+
}
25+
}

0 commit comments

Comments
ย (0)