Article Directory
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 B
the 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 i
is the anterior i-1
-bit multiply accumulate again after n-i
the cumulative position
to accumulate from left to right, the i
previous value of the bit i-1
-bit accumulate
and then from right to left cumulative, the first i
bit is 2. The result is multiplied by the n-i
position of the cumulative
"Prove safety -Offer" given graphic explanation, easy to understand:
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;
}
};