238. Product of Array Except Self
Input: [1,2,3,4]
Output: [24,12,8,6]class Solution {
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
res[0] = 1;
//save the the left product for nums[i] at res[i]
for (int i = 1; i < nums.length; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
// save the final result in res[i] as res[i] * right; update right to be right * nums[i]
int right = 1;
for (int i = nums.length - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}
}Last updated