An array a [n] is known to construct an interesting Algorithm for Array B [N ].

Source: Internet
Author: User

Given an array a [n], we want to construct array B [N], where B [I] = A [0] * A [1] *... * A [N-1]/A [I].
The construction process must meet the following requirements:
1. Division is not used;
2,O (1)Spatial complexity andO (N)Time complexity;
3. In addition to traversing the counters used by a [n] B [N], no new variables (including stack temporary variables, space-based and Global static variables) are used );

 

/*************************************** * ****** // * Specify an array a [n], we want to construct the array B [N], where B [I] = A [0] * A [1] *... * A [N-1]/A [I]. Division is not allowed in the construction process: 1; 2 requires O (1) space complexity and O (n) time complexity; 3. In addition to traversing the counter and a [n] B [N], new variables (including stack temporary variables, space-and Global static variables) cannot be used ); *//************************************* * *******/void makearray (int A [], int B [], int Len) {int I, j; B [0] = 1; for (I = 1; I <Len; I ++) {B [I] = B [I-1] * A [I-1]; // tired ride a [0] * A [1]... A [I-1]} B [0] = A [len-1]; for (j = len-2; j> 0; j --) {B [J] * = B [0]; B [0] * = A [J];}

This question is very common. After reading it, I analyzed it. If in B [N], B [I] = A [0] * A [1] *... * A [N-1]/A [I], then we can consider separately, the implementation code uses two loops, the first loop first implementation,

B1 [I] = A [0] a [1] A [2]… A [I-1], the next cycle from the back to achieve B2 [I] = A [len-1] a [len-2]... A [I + 1], in the second cycle, B [I] = b1 [I] * B2 [I] is implemented due to the constant changes of B [0]. therefore, the question requirement is met. Because the variable cannot be defined in the question, B [0] can be used multiple times.

An array a [n] is known to construct an interesting Algorithm for Array B [N ].

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.