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"