LeetCode: Product of Array Except Self

时间:2021-05-20 20:16:55

Dynamic Programming

 public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] ans = new int[nums.length];
for (int i = 0; i < ans.length; i++) ans[i] = 1;
int product = 1;
for (int i = 1; i < ans.length; i++) {
product *= nums[i-1];
ans[i] *= product;
}
product = 1;
for (int i = ans.length-2; i >= 0; i--) {
product *= nums[i+1];
ans[i] *= product;
}
return ans;
}
}