《剑指offer》——构建乘积数组

题目:
给定一个数组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[i]即为A中除A[i]以外剩下元素的乘积。可以构建两个辅助数组forward和backward,forward用于存储A中前i-1个元素的乘积,back用于存储A中倒数i个(n-i个)元素的乘积,然后再计算B中元素的值。

以数组长度为5为例,A[0]、A[1]、A[2]、A[3]、A[4]。
for[0] = 1
for[1] = for[0]*A[0] = A[0]
for[2] = for[1]*A[1] = A[0]*A[1]
for[3] = for[2]*A[2] = A[0]*A[1]*A[2]
for[4] = for[3]*A[3] = A[0]*A[1]*A[2]*A[3]
back[0] = 1
back[1] = back[0]*A[4] = A[4]
back[2] = back[1]*A[3] = A[3]*A[4]
back[3] = back[2]*A[2] = A[2]*A[3]*A[4]
back[4] = back[3]*A[1] = A[1]*A[2]*A[3]*A[4]

public class Solution {
    public int[] multiply(int[] A) {
        int len = A.length;//数组A的长度
        if(len == 0)//若A为空数组,则返回空
            return null;
        int[] B = new int[len];
        int[] forward = new int[len];
        int[] backward = new int[len];
        forward[0] = 1;//初始化
        backward[0] = 1;
        for(int i = 1; i < len; i++)
        {
            forward[i] = forward[i - 1] * A[i - 1];//构建forward数组
            backward[i] = backward[i - 1] * A[len - i];//构建backward数组
        }
        for(int i = 0; i < len; i++)//构建B数组
        {
            B[i] = forward[i] * backward[len - i - 1];
        }
        return B;
    }
}

你可能感兴趣的:(《剑指offer》——构建乘积数组)