Topic:
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.)
Ideas:
1. Calculate the number of multiplied results, and record "0" in the array
2. Once again facilitate the initial given array, according to the number of "0" and the location of the occurrence of processing
3. When there is only one 0, the result is to get rid of this 0 of the remaining number of the product
4. When there are multiple 0, the result is an array of all zeros
Code:
Public Static int[] Productexceptself (int[] nums) { int[] Arrresult =New int[Nums.length]; intITemp =1; intI0counter=0; for(intI =0;i < nums.length;i++){ if(nums[i]!= 0) {iTemp= ITemp *Nums[i]; } Else{I0counter++; } } if(I0counter ==0 ){ for(intI =0;i < nums.length;i++) {Arrresult[i]= itemp/Nums[i]; } returnArrresult; } Else if(I0counter ==1 ){ for(intI =0;i < nums.length;i++){ if(Nums[i] = = 0) {Arrresult[i]=iTemp; } Else{Arrresult[i]= 0; } } returnArrresult; } Else{ for(intI =0;i < nums.length;i++) {Nums[i]=0; } returnArrresult; } }
Analysis: This solution has a more complex time, uses extra space, and uses division
Idea 2: When traversing the multiplicative, "remove" the element of "current position"
1. Calculate the product of the element to the left of the current position, and record it in the current position of the output array so that no additional storage space is used
2. Iterate from the right, recording the product of all the elements on the right side of the current position, recorded in an additional position
3. Multiply the two arrays one after another
The code is as follows:
Public Static int[] Productexceptself (int[] nums) { int[] Arrresult =New int[Nums.length]; int[] Arrright =New int[Nums.length]; arrresult[0] = 1; for(inti = 1;i<nums.length; i++) {Arrresult[i]= Arrresult[i-1]*nums[i-1] ; } arrright[nums.length-1] = 1; for(inti = nums.length-2; i>= 0; i--) {Arrright[i]= Arrright[i+1]*nums[i+1] ; } for(inti = 0;i<nums.length; i++) {Arrresult[i]= arrresult[i]*Arrright[i]; } returnArrresult; }
[Leetcode]: 238:product of Array Except self