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.)
Idea: Method 1. You can calculate the product product of all the elements, if the product is not 0, then each element corresponds to Product/nums[i], if 0, the element is not 0, the element returned is 0, and the elements of 0 are then traversed by the calculation
Method 2. Maintain two arrays, left[] and right[]. The sum of left[i] and right added to the left of the first and second elements are recorded separately and Right[i]. Then the result res[i] is left[i]+right[i]. Follow up requires O (1) space. Using the returned array of results, first save the right array. The left is computed from the right side, and the resulting value is computed so that no additional space is required. This algorithm is better
Code 1.
Public classSolution { Public int[] Productexceptself (int[] nums) { intProduct =1; for(inti =0; I < Nums. Length; i++) {Product*=Nums[i]; } int[] result =New int[Nums. Length]; if(Product! =0) { for(inti =0; I < Nums. Length; i++) {Result[i]= Product/Nums[i]; } } Else { for(inti =0; I < Nums. Length; i++) { if(Nums[i]! =0) Result[i]=0; Else{Result[i]=1; for(intj =0; J < Nums. Length; J + +) { if(J! =i) result[i]*=Nums[j]; } } } } returnresult; }}
Code 2.
Public classSolution { Public int[] Productexceptself (int[] nums) { int[] res =New int[Nums. Length]; Res[res. Length-1] =1; for(intI=nums. length-2; i>=0; i--) {Res[i]= res[i+1] * nums[i+1]; } intleft =1; for(intI=0; I<nums. Length; i++) {Res[i]*=Left ; Left*=Nums[i]; } returnRes; }}
[LeetCode238] Product of Array Except self