238. Product of Array Except self

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.)


The array, in addition to its own elements, is a product of other elements that form a new array.



Set two integer variables, start=end=1, new return array vector<int> re (Nums.size (), 1);

Multiplies & assigns the current element in the re from the end of the array, respectively

As you traverse one side, each element in the re is exactly what is required.



classSolution { Public: Vector<int> productexceptself (vector<int>&nums) {        if(Nums.empty ())returnvector<int>(); Vector<int> Re (nums.size (),1); intStart =1; intE =1;  for(inti =0;i< (int) nums.size (); i++) {Re[i]*=start; Start*=Nums[i]; Re[nums.size ()-i-1] *=e; E*= nums[nums.size ()-i-1]; }         for(Auto I:re) cout<<i<<" "; cout<<Endl; returnre; }};

238. Product of Array Except self

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.