剑指offer-66 构建乘积数组

剑指offer-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];)

思路:

自己解答:

import java.util.ArrayList;
public class Solution {
    public int[] multiply(int[] A) {
        int[] res = new int[A.length];
        res[0] = 1;
        res[1] = A[0];
        for(int i = 2; i < A.length; i++){
            res[i] = res[i - 1] * A[i - 1];
        }
        int tmp = 1;
        for(int i = A.length -2; i >= 0; i--){
            tmp *= A[i + 1];
            res[i] *= tmp;
        }
        return res;
    }
}

犯的错误:
第二个循环中,需要temp来存乘积

注意:

别人解答:

猜你喜欢

转载自www.cnblogs.com/muche-moqi/p/12393044.html
今日推荐