[Prove safety -Offer] 66. Construction product array (thinking, analog, top Solution)

1. Source title

Links: to build an array of product
Source: LeetCode-- "prove safety -Offer" special

2. Description title

Given an array A[0,1,…,n-1], construct an array B[0,1,…,n-1]in which Bthe elements B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]. You can not use the division.

Example:

Input: [1,2,3,4,5]
Output: [120,60,40,30,24]

prompt:

  • And the sum of the products of all the elements is not 32-bit integer overflow
  • a.length <= 100000

3. resolve title

Method One: Thinking + analog + top Solution

Very clear is that the first iis the anterior i-1-bit multiply accumulate again after n-ithe cumulative position
to accumulate from left to right, the iprevious value of the bit i-1-bit accumulate
and then from right to left cumulative, the first ibit is 2. The result is multiplied by the n-iposition of the cumulative

"Prove safety -Offer" given graphic explanation, easy to understand:
Here Insert Picture Description
Here Insert Picture Description

See the code below:

// 执行用时 :20 ms, 在所有 C++ 提交中击败了93.40%的用户
// 内存消耗 :26.1 MB, 在所有 C++ 提交中击败了100.00%的用户

class Solution {
public:
    vector<int> constructArr(vector<int>& a) {
        int n = a.size();
        vector<int>  vt(n);
        int tmp = 1;
        for(int i = 0; i < a.size(); ++i) {
            vt[i] = tmp;
            tmp *= a[i];
        }
        tmp = 1;
        for(int i = n-1; i >= 0; --i) {
            vt[i] *= tmp;
            tmp *= a[i];
        }
        return vt;
    }
};
Published 343 original articles · won 197 Like · views 60000 +

Guess you like

Origin blog.csdn.net/yl_puyu/article/details/104788599