1.题目
2.解法
public class Solution {
public int[] multiply(int[] A) {
/**
* 可分为左右两部分两乘
* left[i] = A[0] * A[1] * ... * A[i-1]
* right[i] = A[i+1] * A[i+2] * .. *A[n-1]
* B[i] = left[i] * right[i]
*/
int len = A.length;
int[] B = new int[len];
// 因为对角线值都为1
for (int i = 0; i < len; i++) {
B[i] = 1;
}
/**
* 左半部分的规律是
* left[i+1] = A[0] * A[1] * ... A[i]
* left[i+1] = left[i] * A[i]
*/
for (int i = 0; i < len - 1; i++) {
B[i+1] = B[i] * A[i];
}
/**
* 右半部分的规律是
* right[i] = A[i+1] * A[i+2] * ... A[n-1]
* right[i+1] = A[i+2] * A[i+3] * ... A[n-1]
* right[i] = right[i+1] * A[i+1]
*/
int tmp = 1;
for (int i = len - 2 ; i >= 0 ; --i) {
tmp *= A[i+1];
B[i] *= tmp;
}
return B;
}
}
时间复杂度为O(n), 空间复杂度为O(1)