Skip to content

Commit 5f2ae96

Browse files
committed
product of array except self
1 parent 7b9d6ff commit 5f2ae96

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// ํ’€์ด
2+
// ํ˜„์žฌ ์ธ๋ฑ์Šค๊ฐ€ i ์ผ ๋•Œ, ๋ฌธ์ œ์—์„œ ๊ตฌํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฐ’์€ ์•„๋ž˜์™€ ๊ฐ™๋‹ค.
3+
// ๋‚˜์˜ ์™ผ์ชฝ(i-1)๋ถ€ํ„ฐ ์ฒ˜์Œ๊นŒ์ง€์˜ ๊ณฑ * ๋‚˜์˜ ์˜ค๋ฅธ์ชฝ(i+1)๋ถ€ํ„ฐ ๋๊นŒ์ง€์˜ ๊ณฑ
4+
// leftProduct[i-1] = ์™ผ์ชฝ(i-1)๋ถ€ํ„ฐ ์ฒ˜์Œ๊นŒ์ง€์˜ ๊ณฑ
5+
// rightProduct[i+1] = ์˜ค๋ฅธ์ชฝ(i+1)๋ถ€ํ„ฐ ๋๊นŒ์ง€์˜ ๊ณฑ
6+
// leftProduct๋Š” ์ฒ˜์Œ๋ถ€ํ„ฐ i๊นŒ์ง€ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ตฌํ•˜๋ฉด ๋œ๋‹ค. leftProduct[i] = leftProduct[i-1] * (๋‚˜ ์ž์‹  = nums[i])
7+
// rightProduct๋Š” ๋๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ i๊นŒ์ง€ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ตฌํ•˜๋ฉด ๋œ๋‹ค. rightProduct[i] = rightProduct[i+1] * (๋‚˜ ์ž์‹  = nums[i])
8+
9+
10+
// DP ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(N)
11+
// ๊ณต๊ฐ„ ๋ณต์žก๋„๋Š” 2๊ฐœ์˜ ๋ฐฐ์—ด์ด ํ•„์š”ํ•˜๊ณ , ๋‹ต์œผ๋กœ ๋ณด๋‚ผ ๋ฐฐ์—ด๊นŒ์ง€ ํ•ด์„œ O(3*N) = O(N)
12+
13+
class Solution {
14+
public int[] productExceptSelf(int[] nums) {
15+
int len = nums.length;
16+
int[] leftProduct = new int[len];
17+
int[] rightProduct = new int[len];
18+
19+
leftProduct[0] = nums[0];
20+
rightProduct[len - 1] = nums[len - 1];
21+
for (int i = 1; i < len; ++i) {
22+
leftProduct[i] = leftProduct[i - 1] * nums[i];
23+
rightProduct[len - i - 1] = rightProduct[len - i] * nums[len - i - 1];
24+
}
25+
26+
int[] result = new int[len];
27+
result[0] = rightProduct[1];
28+
result[len - 1] = leftProduct[len - 2];
29+
for (int i = 1; i < len - 1; ++i) {
30+
result[i] = leftProduct[i - 1] * rightProduct[i + 1];
31+
}
32+
return result;
33+
}
34+
}
35+

0 commit comments

Comments
ย (0)