File tree Expand file tree Collapse file tree 1 file changed +27
-10
lines changed
Expand file tree Collapse file tree 1 file changed +27
-10
lines changed Original file line number Diff line number Diff line change 11class Solution {
22 public int [] productExceptSelf (int [] nums ) {
3- if (nums == null || nums .length == 0 ) {
4- return new int [] {};
5- }
6-
73 int [] result = new int [nums .length ];
8- int productSoFar = 1 ;
4+
5+ boolean hasZero = false ;
6+ int product = 1 , zeroIdx = 0 ;
97
108 for (int i = 0 ; i < nums .length ; i ++) {
11- result [i ] = productSoFar ;
12- productSoFar *= nums [i ];
9+ if (nums [i ] == 0 ) {
10+ if (hasZero ) {
11+ return new int [nums .length ];
12+ }
13+
14+ hasZero = true ;
15+ zeroIdx = i ;
16+ continue ;
17+ }
18+
19+ result [i ] = product ;
20+ product *= nums [i ];
1321 }
1422
15- productSoFar = 1 ;
23+ product = 1 ;
1624
1725 for (int i = nums .length - 1 ; i >= 0 ; i --) {
18- result [i ] *= productSoFar ;
19- productSoFar *= nums [i ];
26+ if (nums [i ] == 0 ) {
27+ continue ;
28+ }
29+
30+ result [i ] *= product ;
31+ product *= nums [i ];
32+ }
33+
34+ if (hasZero ) {
35+ Arrays .fill (result , 0 );
36+ result [zeroIdx ] = product ;
2037 }
2138
2239 return result ;
You can’t perform that action at this time.
0 commit comments