File tree 1 file changed +34
-0
lines changed
product-of-array-except-self
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ class SolutionProductExceptSelf {
2
+
3
+ public int [] productExceptSelf (int [] nums ) {
4
+ // answer[i] = nums[0] * nums[1] * ... * nums[i-1] * nums[i+1] * ... * nums[n-1]
5
+ // answer[i] = left[i] * right[i]
6
+ // left[i] = nums[0] * nums[1] * ... * nums[i-1]
7
+ // right[i] = nums[i+1] * ... * nums[n-1]
8
+ // left[i] = left[i-1] * nums[i-1]
9
+ // right[i] = right[i+1] * nums[i+1]
10
+ // answer[i] = left[i] * right[i]
11
+ // 시간복잡도: O(N), 공간복잡도: O(N)
12
+ int n = nums .length ;
13
+ int [] left = new int [n ];
14
+ int [] right = new int [n ];
15
+ int [] answer = new int [n ];
16
+
17
+ left [0 ] = 1 ;
18
+ right [n - 1 ] = 1 ;
19
+
20
+ for (int i = 1 ; i < n ; i ++) {
21
+ left [i ] = left [i - 1 ] * nums [i - 1 ];
22
+ }
23
+
24
+ for (int i = n - 2 ; i >= 0 ; i --) {
25
+ right [i ] = right [i + 1 ] * nums [i + 1 ];
26
+ }
27
+
28
+ for (int i = 0 ; i < n ; i ++) {
29
+ answer [i ] = left [i ] * right [i ];
30
+ }
31
+
32
+ return answer ;
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments