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