劍指offer-51:構建乘積陣列
阿新 • • 發佈:2018-12-18
題目描述
給定一個數組A[0,1,…,n-1],請構建一個數組B[0,1,…,n-1],其中B中的元素B[i]= A[0] x A[1] x … x A[i-1] x A[i+1] x … x A[n-1]。不能使用除法。
思路
由題目可知B[i]=A[0] x A[1] x … x A[n-1]/A[i]。題目裡面不能用除法
程式碼實現
public class Solution51 {
public int[] multiply(int[] A) {
if (A == null || A.length == 0)
return null;
int len = A.length;
int[] result = new int[len];
result[0] = 1;//預設初始化是1
//計算左邊的三角 也就是C[i]
for (int i = 1; i < len; i++) {
result[i] = result[i - 1] * A[i - 1];
}
//計算右邊的三角 也就是D[i]
int temp = 1;//預設初始化值
for (int i = len - 2; i >= 0; i--) {
temp *= A[i + 1];
result[i] *= temp;
}
return result;
}
public static void main(String[] args) {
int[] arr = {1, 3, 4, 1, 4, 3, 5, 1, 3, 5, 1};
BeanUtil.print(Arrays.toString(new Solution51().multiply(arr) ));
}
}