假设:
left[i] = A[0]...*A[i-1]
right[i] = A[i+1]...*A[n-1]
所以:
B[i] = left[i] * right[i]
所以我们可以先算出left[i],然后再算出right[i]
left[i] = left[i-1] X A[i-1]
right[i] = A[i+1] X right[i-1]
public int[] multiply(int[] A) { int n = A.length; int[] B = new int[n]; B[0] = 1; // 现在B[i] 相当于left[i] for(int i = 1; i < n; i++){ B[i] = B[i-1]*A[i-1]; } int tmp = 1; // 最后一个刚开始是1 //从倒数第二个算起 for(int i = n-2; i >= 0; --i){ // tmp相当于right[i] tmp *= A[i+1]; //相当于 B[i] = left[i] * right[i] B[i] *= tmp; } return B; }