2020-2-23
Links: prove safety offer_ bovine construct in the product array guest net _
Title Description:
Given an array A [0,1, ..., n- 1], please construct an array B [0,1, ..., n- 1], wherein the element B is B [i] = a [0 ] * a [1] * ... * a [i-1] * a [i + 1] * ... * a [n-1]. You can not use the division. (Note: The predetermined B [0] = A [1 ] * A [2] * ... * A [n-1], B [n-1] = A [0] * A [1] * ... * A [n -2];)
ideas:
time complexity of O (N) O (N)
can be B [i] = A [0 ] A [1] ... A [i-1] A [i + 1] ... A [ n-1]. As A [0] A [1] ... A [i-1] and A [i + 1] ... A [n-2] A [n-1] is the product of two parts.
I.e. by the product of the B [i] is divided into two parts A [i] item. Effect is equivalent to a diagonal matrix.
The first for loop is used to calculate the number of the FIG. 1 range, the second for loop is used to calculate the number range of 2 to FIG.
Code:
class Solution {
public:
vector<int> multiply(const vector<int>& A) {
vector<int> B;
int len = A.size();
B.push_back(1);
for(int i = 1; i < len; i++){
B.push_back(A[i-1] * B[i-1]);
}
int temp = 1;
for(int i = len-1; i > 0; i--){
temp *= A[i];
B[i-1] *= temp;
}
return B;
}
};