Leetcode 238 Product of array Except self (the product of the remainder of the array in addition to itself)

Source: Internet
Author: User

translation
给定一个有n个数字的数组nums,其中n大于1,返回一个数组使得output[i]等于除nums[i]外所有元素的乘积。不用分治并且在O(n)复杂度下解决这个问题。例如,给定[1, 2, 3, 4],返回[24, 12, 8, 6]。跟进:你可以只在常量空间下完成它吗?(备注:在空间复杂度计算时输出数组不作为额外空间。)
Original
Given an array ofn integerswheren >1, Nums,returnAn array output such thatOutput[i] is Equal  to  theProduct ofAll theElements ofNums except Nums[i]. Solveit withoutDivision and inchO (n). For example,given[1,2,3,4],return[ -, A,8,6]. Follow up:could You solveit  with constant SpaceComplexity? (note:the output Arraydoes  not Count  asExtraSpace  for  thePurpose of SpaceComplexity analysis.)
Analysis

Actually did a similar topic before, but can't remember which question.

See the constant space of the topic to think of the same as before, the product of all the elements are saved, and finally another one in addition to the good is not it?

However, there are problems ...

If the array has a 0 lat?

If the index is indexed, then Output[index] is the product of all the remaining elements, that is, the product of 0 is not calculated.

All remaining elements of the output array are 0.

If there are two or more in the array 0 lat?

Don't say anything, just initialize it to 0.

If the array does not have 0 lat?

That's not a thank goodness, just a single one except for the vector.

Code
classSolution { Public: vector<int>Productexceptself ( vector<int>& Nums) {intCount =0;intPro =1; for(inti =0; I < nums.size (); i++) {if(Nums[i] = =0) count++;ElsePro *= Nums[i]; }if(Count = =1) { vector<int>Res for(inti =0; I < nums.size (); i++) {if(Nums[i] = =0) Res.push_back (PRO);ElseRes.push_back (0); }returnRes }Else if(Count >=2) { vector<int>Res (nums.size ());returnRes }Else{ vector<int>Res for(inti =0; I < nums.size (); i++) Res.push_back (Pro/nums[i]);returnRes }           }};

Leetcode 238 Product of array Except self (the product of the remainder of the array in addition to itself)

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.