[Leetcode] Product of array Except Self in addition to the product of an array

Source: Internet
Author: User

Given an array of n integers where n > 1, nums and return an array output such that's equal to output[i] th E product of all the elements of nums except nums[i] .

Solve it without division and in O (n).

For example, given [1,2,3,4] , return [24,12,8,6] .

Follow up:
Could solve it with constant space complexity? (note:the output array does not count as extra space for the purpose of space complexity analysis.)

Given an array of us, let's return a new array, the number of each position is the product of the number of other positions, and limit the time complexity O (n), and do not let us use division. If you use division, then this problem should be easy, because you can go through the array to find out the product of all numbers, and then divided by the number of the corresponding position. But this problem forbids us to use division, then we can only go the other way. We can walk through the array first, and the product of all the numbers before each position. Then again, the last position on the number is the product of all the previous numbers, is in line with the title, but all the previous numbers need to continue to multiply. We're going to scan back and forth, multiplying the number in each position by the product of all the numbers in the back, and for the last position, multiply by 1, because there are no numbers behind it. See the code below:

classSolution { Public: Vector<int> productexceptself (vector<int>&nums) {Vector<int> Res (nums.size (),1);  for(inti =1; I < nums.size (); ++i) {res[i]= Res[i-1] * Nums[i-1]; }        intright =1;  for(inti = nums.size ()-1; I >=0; --i) {res[i]*=Right ; Right*=Nums[i]; }        returnRes; }};

Leetcode all in one topic summary (continuous update ...)

[Leetcode] Product of array Except Self in addition to the product of an 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.