Topic description Given an array a[0,1,..., n-1], build an array b[0,1,..., n-1], where the elements in B b[i]=a[0]*a[1]*...*a[i-1]*a[i+1]*...*a[n-1]. You cannot use division. Harvest: The formula to think clearly before the program will be clear thinking, write the program quickly.
B[0] |
1 |
A[1] |
A[2] |
A[N-1] |
B[1] |
A[0] |
1 |
A[2] |
A[N-1] |
....... |
A[0] |
A[1] |
A[2] |
A[N-1] |
B[n-2] |
A[0] |
A[1] |
1 |
A[N-1] |
B[N-1] |
A[0] |
A[1] |
A[2] |
1 |
B[i] can be divided into two parts, the left is multiplied to the right, b[i] = l[i] * R[i]; L[0] = 1,l[i] = l[i-1] * A[i-1]; R[n-1] = 1,r[i] = r[i + 1] * a[i + 1]; In this case, the for loop will not write the wrong boundary and initialization condition when calculating, note that because the division cannot be used, L will calculate from 0, and R will be calculated from the bottom up. Next consider the optimization, only with a vector on it, the left side of the traversal, and then directly from the lower right corner to multiply the calculation results.
classSolution { Public: Vector<int> Multiply (Constvector<int>&A) {if(A.empty ()) {return {}; } Vector<int> Res (a.size (),1); intTMP =1; for(inti =1; i < a.size (); + +i) {tmp*= A[i-1]; Res[i]=tmp; } tmp=1; for(inti = a.size ()-2; I >=0;--i) {tmp*= A[i +1]; Res[i]*=tmp; } returnRes; }};
classSolution { Public: Vector<int> Multiply (Constvector<int>&A) {if(A.empty ()) {return {}; } Vector<int>Res (a.size ()); Vector<int> L (a.size (),1), R (A.size (),1); intls =1, rs =1; //L.push_back (1); for(inti =1; i < a.size (); + +i) {ls*= A[i-1]; L[i]=ls; } for(inti = a.size ()-2; I >=0;--i) {RS*= A[i +1]; R[i]=rs; } for(inti =0; i < a.size (); + +i) {Res[i]= L[i] *R[i]; } returnRes; }};
48 Building a product array