238. Product of Array Except Self
#array
Last updated
#array
Last updated
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] answer = new int[nums.length];
// calculate the product till now from the end
answer[nums.length - 1] = 1;
int productTillNow = nums[nums.length - 1];
for (int i = nums.length - 2; i >= 0; --i) {
answer[i] = productTillNow;
productTillNow *= nums[i];
}
// calculate the product till now from the start
int productTillNowFront = 1;
for (int i = 0; i < nums.length; ++i) {
int temp = nums[i];
answer[i] = productTillNowFront * answer[i];
productTillNowFront *= temp;
}
return answer;
}
}