0238. Product of Array Except Self
Description
**Input:** nums = [1,2,3,4]
**Output:** [24,12,8,6]**Input:** nums = [-1,1,0,-3,3]
**Output:** [0,0,9,0,0]ac
Last updated
**Input:** nums = [1,2,3,4]
**Output:** [24,12,8,6]**Input:** nums = [-1,1,0,-3,3]
**Output:** [0,0,9,0,0]Last updated
// most important clue: break into left * right, which hard to come up with
class Solution {
public int[] productExceptSelf(int[] nums) {
// left * right
// walk -> int[] left
// walk backwards -> right * left
// corner cases, no here, n>1
// int[] left
int[] left = new int[nums.length];
left[0] = 1;
for (int i = 1; i < nums.length; i++) {
left[i] = left[i-1] * nums[i-1];
}
// right * left
int right = 1;
left[left.length - 1] *= right;
for (int i = left.length - 1 - 1; i >= 0; i--) {
right *= nums[i+1];
left[i] = left[i] * right;
}
// return left
return left;
}
}