Question 52: Building a product array

Source: Internet
Author: User

Topic:

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.

Ideas:

Method 1:

Direct multiplication n-1 number, get b[i];

Complexity of Time: O (n^2)

Method 2:

Constructs a forward product array c[i]=a[0]*a[1]*...*a[i-1], or c[i]=c[i-1]*a[i-1];

Build the back-to-product array d[i]=a[n-1]*a[n-2]* ... A[n-i+1], i.e. d[i]=d[i+1]*a[i+1];

by C[i],d[i] to seek b[i]:b[i]=c[i]*d[i]

Time complexity: O (N)

Code:
void Multiply (const vector<double>& array1,vector<double>& array2) {    int len1=array1.size ();    int len2=array2.size ();    if (len1==len2 && len2>1) {        array2[0]=1;        for (int i=1;i<len1;i++) {            array2[i]=array2[i-1]*array1[i-1];        }        Double tmp=1;        for (int i=len1-2;i>=0;i--) {            tmp*=array1[i+1];            array2[i]*=tmp;}}}    
Online test OJ:

Http://www.nowcoder.com/books/coding-interviews/94a4d381a68b47b7a8bed86f2975db46?rp=3

AC Code:

class solution {public:vector<int> Multiply (const vector<int>&        A) {int len=a.size ();        if (len<1) return vector<int> ();                Vector<int> B (len,1);        for (int i=1;i<len;i++) {b[i]*=b[i-1]*a[i-1];        } int tmp=1;            for (int i=len-2;i>=0;i--) {tmp*=a[i+1];        b[i]*=tmp;        } return B; }};
Class Solution {public:    vector<int> Multiply (const vector<int>& A) {    int len=a.size ();        if (len<1)            return vector<int> ();        Vector<int> B (len,1);        Vector<int> Front (len,1);        Vector<int> back (len,1);                for (int i=1;i<len;i++) {            front[i]=front[i-1]*a[i-1];        }                for (int i=len-2;i>=0;i--) {            back[i]=back[i+1]*a[i+1];        }                for (int i=0;i<len;i++)            b[i]=front[i]*back[i];                return B;        };

Question 52: 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.