48 Building a product array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.