题目
238. 除自身以外数组的乘积
题解
构造两个数组left和right
left[i] = nums[0] * nums[1] *…… * nums[i-2] * nums[i-1]
right[i] = nums[i + 1] * nums[i + 2] *…… * nums[len-2] * nums[len-1]
所以就有以下的公式:
left[i] = left[i - 1] * nums[i - 1]
right[i] = right[i + 1] * nums[i + 1]
然后最后的结果数组ans
ans[i] = left[i] * right[i]
public int[] productExceptSelf(int[] nums) {
int len = 0;
if (nums == null || (len = nums.length) == 0) {
return null;
}
int[] left = new int[len];
int[] right = new int[len];
int[] ans = new int[len];
Arrays.fill(left, 1);
Arrays.fill(right, 1);
for (int i = 1; i < len; i++) {
left[i] = left[i - 1] * nums[i - 1];
}
for (int i = len - 2; i >= 0; i--) {
right[i] = right[i + 1] * nums[i + 1];
}
for (int i = 0; i < len; i++) {
ans[i] = left[i] * right[i];
}
return ans;
}