File tree Expand file tree Collapse file tree 1 file changed +11
-15
lines changed Expand file tree Collapse file tree 1 file changed +11
-15
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int [] productExceptSelf (int [] nums ) {
3
3
int [] result = new int [nums .length ];
4
-
4
+ int product = 1 ;
5
+ int zeroIdx = -1 ;
5
6
boolean hasZero = false ;
6
- int product = 1 , zeroIdx = 0 ;
7
7
8
8
for (int i = 0 ; i < nums .length ; i ++) {
9
9
if (nums [i ] == 0 ) {
10
10
if (hasZero ) {
11
11
return new int [nums .length ];
12
12
}
13
13
14
- hasZero = true ;
15
14
zeroIdx = i ;
16
- continue ;
15
+ hasZero = true ;
16
+ } else {
17
+ result [i ] = product ;
18
+ product *= nums [i ];
17
19
}
20
+ }
18
21
19
- result [i ] = product ;
20
- product *= nums [i ];
22
+ if (hasZero ) {
23
+ Arrays .fill (result , 0 );
24
+ result [zeroIdx ] = product ;
25
+ return result ;
21
26
}
22
27
23
28
product = 1 ;
24
29
25
30
for (int i = nums .length - 1 ; i >= 0 ; i --) {
26
- if (nums [i ] == 0 ) {
27
- continue ;
28
- }
29
-
30
31
result [i ] *= product ;
31
32
product *= nums [i ];
32
33
}
33
34
34
- if (hasZero ) {
35
- Arrays .fill (result , 0 );
36
- result [zeroIdx ] = product ;
37
- }
38
-
39
35
return result ;
40
36
}
41
37
}
You can’t perform that action at this time.
0 commit comments