File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+
You canโt perform that action at this time.
0 commit comments