剑指Offer(Java版)第五十七题:给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1], 其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。 不能使用除法。(注意:规定B[0] = A[1] * A[2] * ... * A[n-1],B[n-1] = A[0] * A[1] * ... * A[n-2];)

/*
给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],
其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。
不能使用除法。(注意:规定B[0] = A[1] * A[2] * ... * A[n-1],B[n-1] = A[0] * A[1] * ... * A[n-2];)
*/

import java.util.ArrayList;

public class Class57 {

public int[] multiply(int[] A){
if(A == null || A.length <= 0){
return A;
}
int[] B = new int[A.length];
B[0] = 1;
int temp = 1;
for(int i = 1; i < A.length; i++){
B[i] = B[i - 1] * A[i - 1];
}
for(int j = A.length - 2; j >= 0; j--){
temp = temp * A[j + 1];
B[j] = B[j] * temp;
}
return B;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

猜你喜欢

转载自www.cnblogs.com/zhuozige/p/12542205.html
今日推荐