Nine-chapter algorithm surface test 40 do not use Division to calculate the product

Source: Internet
Author: User
Nine chapters count judges Net-original website

http://www.jiuzhang.com/problem/40/


Topic

Given an array of A[1..N], find array B[1..N], make b[i] = a[1] * a[2]. * A[i-1] * a[i+1].. * A[n]. It is required not to use division and to complete in O (n), using an extra space of O (1) (which does not contain space occupied by the B array).


Answer

Calculate prefix product Prefix[i] = a[1] * a[2]. A[i], compute suffix product suffix[i] = a[i] * a[i+1]. A[n], easy to know, b[i] = prefix[i-1] * suffix[i + 1]. In fact, there is no need to actually construct the prefix and suffix arrays, use the B array to iterate from left to right once to get prefix[i], and then iterate from right to left to calculate the required B array.


Interviewer Angle

This method (Foward-backward-traverse), which is traversed from the front to the back and then traversed from the back to the front, is used for reference in many topics. such as the nine-chapter algorithm surface Question 31 sub-array of the maximum difference.

Nine-chapter algorithm surface test 40 do not use Division to calculate the product

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.