Leetcode "Product of Array Except self"

Source: Internet
Author: User

Question 1:without Division. We can simply compose left\right accumulated product arrays:

typedefLong LongLL;classSolution { Public: Vector<int> productexceptself (vector<int>&nums) {size_t len=nums.size (); Vector<LL>Left (len), right (LEN); left[0] = nums[0];  for(inti =1; I < Len-1; i++) Left[i]= nums[i] * left[i-1]; Right[len-1] =Nums.back ();  for(inti = len-2; i >0; i--) Right[i]= nums[i] * right[i +1]; Vector<int>ret (len);  for(inti =0; i < Len; i++) {LL L= (!i)?1: Left[i-1]; LL R= (i = = Len-1) ?1: Right[i +1]; Ret[i]= L *R; }        returnret; }};

Follow-up question:constant Space-we can remove right<int>

classSolution { Public: Vector<int> productexceptself (vector<int>&nums) {size_t len=nums.size (); Vector<int>ret (len); ret[0] = nums[0];  for(inti =1; I < Len-1; i++) Ret[i]= nums[i] * ret[i-1]; intright =1;  for(inti = len-1; I >=0; I--) {Ret[i]= (i >0? Ret[i-1] :1) *Right ; Right*=Nums[i]; }        returnret; }};

Third Solution:sliding window, but could not be quite optimized if there ' s 0

typedefLong LongLL;classSolution { Public: Vector<int> productexceptself (vector<int>&nums) {size_t len=nums.size (); Vector<int>ret (len); intslot = Len-1; LL Pro=1;  for(inti =0; I < Len-1; i++) Pro*=Nums[i];  for(inti =0; i < Len; i++)//start Inx{Ret[slot]=Pro; if(nums[i]!=0) Pro/=Nums[i]; Else{Pro=1;  for(intj = i +1; J < i +1+ Len-2; J + +) Pro*= Nums[j%Len]; } Pro*=Nums[slot]; Slots= (slot +1) %Len; }        returnret; }};

Leetcode "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.