Given array a [N] to construct array B [N] -- Tencent Test

Source: Internet
Author: User

Given an array a [N], we want to construct array B [N], where B [j] = a [0] * a [1]… A [N-1]
/A [j], division is not allowed in the construction process: requires O (1) space complexity and O (n) time complexity; in addition to traversing the counter and a [N]
New variables (including stack temporary variables, heap space and global static variables) cannot be used outside B [N)

 

Resolution: Set B [0] = 1

Available from B [I] = B [I-1] * a [I-1]

B [1] = a [0]

B [2] = a [0] a [1]

...

B [I] = a [0] a [1] a [2]… A [I-1]

...

B [n-1] = a [0] a [1]… A [N-2]

Then, through the variable B [0] To iterate out 1, a [n-1], a [N-2] a [n-1], a [n-3] a [N-2] a [n-1],... , A [1] a [2] a [3]… A [n-1], multiplied by B [n-1], B [N-2],
... , B [0]

The Code is as follows:

void Translate(int a[], int b[], int n){b[0] = 1;for (int i = 1; i <= n-1; i++){b[i] = b[i-1]*a[i-1];}for (int i = n-1; i >= 1; i--){b[i] *= b[0];b[0] *= a[i];}}

 

The test code is as follows:

int main(){int a[] = {2,3,4,5};int b[] = {0,0,0,0};Translate(a,b,4);for(int i = 0; i < 4; i++)cout << a[i] << "\t";cout << endl;for(int i = 0; i < 4; i++)cout << b[i] << "\t";cout << endl;system("pause");return 0;}

 

The result is as follows:


 

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.