Skip to content

Commit 4f37768

Browse files
committed
modify code
1 parent ee9ae97 commit 4f37768

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

src/topinterviewquestions/Problem_0238_ProductOfArrayExceptSelf.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,21 @@ public int[] productExceptSelf(int[] nums) {
2929
}
3030
return nums;
3131
}
32+
33+
public int[] productExceptSelf2(int[] nums) {
34+
int n = nums.length;
35+
int[] ans = new int[n];
36+
ans[0] = nums[0];
37+
for (int i = 1; i < n; i++) {
38+
ans[i] = ans[i - 1] * nums[i];
39+
}
40+
int right = 1;
41+
for (int i = n - 1; i > 0; i--) {
42+
ans[i] = ans[i - 1] * right;
43+
right *= nums[i];
44+
}
45+
ans[0] = right;
46+
return ans;
47+
}
3248

3349
}

0 commit comments

Comments
 (0)