Google: Calculate a [0] * A [1] *… * A [n-1]/A [I]

Source: Internet
Author: User

Free don't take a look at this blog: http://jonnyhsy.wordpress.com/category/algorithms-data-structure/

// Given an array a [n], build another array B [N], B [I] = A [0] * A [1] *… * A [n-1]/A [I]
// No division can be used, O (n) time complexity

See the webpage:

Http://www.ihas1337code.com/2010/04/multiplication-of-numbers.html

Let's define array B where Element B [I] = multiplication of numbers from a [0] to a [I]. for example, if a = {4, 3, 2, 1, 2}, then B = {4, 12, 24, 24, 48 }. then, we scan the array a from right to left, and have a temporary variable called product which stores the multiplication from right to left so far. calculating output [I] is straight forward, as output [I] = B [I-1] * product.

The above method requires only O (n) TimeBut uses O (n) space. We have to trade memory for speed.Is there a better way?(I. e., runs in O (n) time but without extra space ?)

Yes, actually the temporary table is not required. we can have two variables called left and right, each keeping track of the product of numbers multiplied from left-> right and right-> left. cocould you see why this works without extra space?

void array_multiplication(int A[], int OUTPUT[], int n)
{
int left = 1;
int right = 1;
for (int i = 0; i < n; i++)
OUTPUT[i] = 1;
for (int i = 0; i < n; i++) {
OUTPUT[i] *= left;
OUTPUT[n - 1 - i] *= right;
left *= A[i];
right *= A[n - 1 - i];
}
}

SELF: http://jonnyhsy.wordpress.com/2011/05/03/google-%E8% AE %A1%E7% AE %97a0a1-an-1ai/

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.