"Sword Finger Offer" Question 66: Constructing Product Array

// Interview question 66: Building an array of products
 // Question: Given an array A [0, 1,…, n-1], please build an array B [0, 1,…, n-1], which
 // The element B [i] = A [0] × A [1] ×… × A [i-1] × A [i + 1] ×… × A [n-1] in B. You cannot use division. 

#include <cstdio> 
#include <vector> using namespace std;
 // Take B [i] as [= A [0], A [1],…, A [i-1], 1, A [i + 1],…, A [n-1]]
 // For B, it becomes a two-dimensional array, for 1 is the upper triangular matrix on the left, and the lower triangular matrix on the right
 /// The product value of each row of the triangular matrix can be calculated from the top Down void BuildProductionArray ( const vector < double > & input, vector < double > & output) 
{ int length1 = input.size ();
     int length2 =

 

    output.size (); 

    if (length1 == length2 && length2> 1 ) 
    { 
        output [ 0 ] = 1 ;
         for ( int i = 1 ; i <length1; ++ i) 
        { 
            output [i] = output [i- . 1 ] * INPUT [I - . 1 ]; // computing each row of the left triangular matrix multiplication value 
        } 

        Double TEMP = . 1 ;
         for ( int I = length1 - 2 ; I> = 0 ; Inc. (www.i-levelmedia.com)) // note two I initialization value
         {
            temp * = input [i + 1 ]; // Calculate the product value of each row of the lower triangular matrix 
            output [i] * = temp; // The multiplied value of the peers of the upper and lower triangles is multiplied again, which is B [i] Valued 
        } 
    } 
}

 

Guess you like

Origin www.cnblogs.com/ZSY-blog/p/12695113.html