第51题——构建乘积数组

167 阅读1分钟

题目:

给定一个数组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]。不能使用除法。

思路:

不能使用除法,那么就考虑分两步来乘,i之前的乘法preMultiply(),和i之后的乘法afterMultiply()。

Java

package nowcoder;

public class S51_Multiply {
    public int[] multiply(int[] A){
        int length = A.length;
        int[] B = new int[length];
        for (int i=0;i<length;i++){
            B[i] = preMultiply(A, i) * afterMultiply(A, i);
        }
        return B;
    }
    private int preMultiply(int[] A, int a){
        int pre = 1;
        for (int i=0;i<a;i++)
            pre *= A[i];
        return pre;
    }
    private int afterMultiply(int[] A, int a){
        int after = 1;
        for (int i=A.length-1;i>a;i--)
            after *= A[i];
        return after;
    }
    public static void main(String[] args){
        S51_Multiply s51 = new S51_Multiply();
        int[] A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] res = s51.multiply(A);
        for (int i=0;i<res.length;i++)
            System.out.print(res[i]+" ");
    }
}

Java 思路二

package nowcoder;

public class S51_Multiply_new {
    public int[] multiply(int[] A){
        int length = A.length;
        int[] B = new int[length];
        for (int i=0;i<length;i++){
            int temp = A[i];
            B[i] = 1;
            for (int j=0;j<length;j++){
                A[i] = 1;
                B[i] *= A[j];
            }
            A[i] = temp;//还原A[i],否则A[i]就是1了
        }
        return B;
    }
    public static void main(String[] args){
        S51_Multiply_new s51 = new S51_Multiply_new();
        int[] A = {1, 2, 3, 4};
        int[] res = s51.multiply(A);
        for (int i=0;i<res.length;i++)
            System.out.print(res[i]+" ");
    }
}

Python

class Multiply:
    def multiply(self, A):
        length = len(A)
        B = []
        for i in range(length):
            temp = A[i]
            b = 1
            for j in range(length):
                A[i] = 1
                b *= A[j]
            B.append(b)
            A[i] = temp
        return B
if __name__ == '__main__':
    test = Multiply()
    A = [1, 2, 3, 4, 5]
    print(test.multiply(A))