import java.util.Arrays;
/**
* 面试题66:构建乘积数组
* 给定一个数组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长度为1的情况,B无意义,故而无法构建,因此该情况不会存在。
*
* 输入:[1,2,3,4,5]
* 输出:[120,60,40,30,24]
*
* B[0]=A[1]*A[2]*A[3]*A[4]
* B[1]=A[0]*A[2]*A[3]*A[4]
* B[2]=A[0]*A[1]*A[3]*A[4]
* B[3]=A[0]*A[1]*A[2]*A[4]
* B[4]=A[0]*A[1]*A[2]*A[3]
*
* @author dengjie
* @create 2021-04-17 21:12
*/
public class Solution66 {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
int[] multiply = multiplyTwo(arr);
System.out.println(Arrays.toString(multiply));
}
/**
* 方法一:两个for循环相乘
* @param A
* @return
*/
public static int[] multiply(int[] A) {
if (A == null || A.length == 0 || A.length == 1){
return null;
}
int[] res = new int[A.length];
Arrays.fill(res, 1);
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
if (j!=i){
res[i] *= A[j];
}
}
}
return res;
}
/**
* 方法二:时间复杂度为O(n)的解法
* 思路:可以把B[i]=A[0]A[1]....A[i-1]A[i+1]....A[n-1]。
* 看成A[0]A[1].....A[i-1]和A[i+1].....A[n-2]A[n-1]两部分的乘积。
* left[i] = left[i-1]*A[i-1];//C[i]
* right[i] = right[i+1]*A[i+1]//D[i]
* res[i] = C[i]*D[i]
* @param A
* @return
*/
public static int[] multiplyTwo(int[] A) {
if (A == null || A.length == 0 || A.length == 1){
return null;
}
int[] res = new int[A.length];
//初始化res[0]
res[0] =1;
//计算下三角乘积C[i],拿到左边部分的乘积
for (int i = 1; i < A.length; i++) {
res[i] = res[i-1] * A[i-1];
}
//初始化
int temp = 1;
//计算上三角乘积D[i],由于最后一个已经计算完,所以从res[A.length-2]开始
for (int i = A.length-2;i>=0;i--){
//temp =temp*A[i+1]; temp就是i位置对应的右边部分的值 从A[n-1]一直乘到A[1]
temp *= A[i+1];
res[i] *= temp;//res[i]为左边乘积*右边乘积
}
return res;
}
}
【剑指Offer】面试题66:构建乘积数组
最新推荐文章于 2022-03-25 20:56:10 发布