Given an integers array A.
Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], calculate B WITHOUT divide operation.
Example
For A = [1, 2, 3]
, return [6, 3, 2]
.
分析:
public class Solution {
public int[] productExceptSelf(int[] A) {
int[] left = new int[A.length];
int[] right = new int[A.length];
int[] result = new int[A.length]; for (int i = ; i < A.length; i++) {
left[i] = i == ? : left[i - ] * A[i - ];
right[A.length - - i] = (i == ) ? : right[A.length - i] * A[A.length - i];
} for (int i = ; i < A.length; i++) {
result[i] = left[i] * right[i];
}
return result;
}
}
public class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
res[] = ;
for (int i = ; i < n; i++) {
res[i] = res[i - ] * nums[i - ];
}
int right = ;
for (int i = n - ; i >= ; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}
}
one pass
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
Arrays.fill(result, );
int left = , right = ;
for (int i = , j = nums.length - ; i < nums.length - ; i++, j--) {
left *= nums[i];
right *= nums[j];
result[i + ] *= left;
result[j - ] *= right;
}
return result;
}
}