File tree Expand file tree Collapse file tree 1 file changed +30
-13
lines changed Expand file tree Collapse file tree 1 file changed +30
-13
lines changed Original file line number Diff line number Diff line change 3
3
//In first pass calculate the left product except self and in second calculate the right
4
4
5
5
class Solution {
6
+ public int [] productExceptSelf (int [] nums ) {
7
+ int [] arr = new int [nums .length ];
8
+ int right = 1 , left = 1 ;
9
+ for (int i = 0 ; i < nums .length ; i ++) {
10
+ arr [i ] = left ;
11
+ left *= nums [i ];
12
+ }
13
+ for (int i = nums .length - 1 ; i >= 0 ; i --) {
14
+ arr [i ] *= right ;
15
+ right *= nums [i ];
16
+ }
17
+ return arr ;
18
+ }
6
19
7
- public int [] productExceptSelf (int [] nums ) {
8
- int [] arr = new int [nums .length ];
9
- int right =1 , left =1 ;
10
- for (int i = 0 ; i < nums .length ; i ++) {
11
- arr [i ] = left ;
12
- left *= nums [i ];
13
- }
14
- for (int i = nums .length - 1 ; i >= 0 ; i --) {
15
- arr [i ] *= right ;
16
- right *= nums [i ];
17
- }
18
- return arr ;
19
- }
20
+ // using nums[] as the prefix calculation table
21
+ public int [] productExceptSelfNumsAsPrefix (int [] nums ) {
22
+ int [] output = new int [nums .length ];
23
+ output [0 ] = 1 ; // default prefix is 1.
24
+
25
+ // prefix
26
+ for (int i = 0 ; i < nums .length - 1 ; i ++)
27
+ output [i + 1 ] = output [i ] * nums [i ];
28
+
29
+ // postfix
30
+ // we start at nums.length - 2 because multiplying by 1 is silly.
31
+ for (int i = nums .length - 2 ; i >= 0 ; i --) {
32
+ output [i ] = nums [i + 1 ] * output [i ];
33
+ nums [i ] = nums [i ] * nums [i + 1 ];
34
+ }
35
+ return output ;
36
+ }
20
37
}
You can’t perform that action at this time.
0 commit comments