problem:
return An array output such this output[i] is equal to the product of all the elements of nums except]. Solve it without division and in O (n). For example, given [return [24,12,8,6]. Follow up:could you solve it with constant space complexity for the purpose of space complexity analysis.)
Analysis:
This problem is very good!It involves the test against coding skills and simple dynamic programming!Basic Idea:since We were asked to compute the"Product of whole array except self", and we were not allowed to use division. The instant idea was to:--------------------------------------------------Right product exclude I*Left product exclude I---------------------------------------------------Apparently, we need, arrays forthose information. And we were only allowed to use constant space. We have the advantage of the"Nums array" and "res array". To take advantage of existing array, you must is very careful with direction and order. Otherwise would mess up all existing information. for ThisProblem, I use "res array" forleft-to-Right direction. for(inti = 1; i < Len; i++) Res[i]= nums[i] * res[i-1];"Nums Array" forRight -to-left direction. for(inti = len-2; I >= 0; i--) Nums[i]= nums[i+1] *Nums[i]; Since the"Right-to-left" computation would overwrite "nums array", the "res array"must be calculated firstly. When left and right array are ready, we could calculate theFinalresult.intleft = ((i = = 0)? 1:res[i-1]);intright = ((i = = len-1)? 1:nums[i+1]); Res[i]= left *Right ;***************************note:since when calculate res[i] (overall product), we need to use res[i-1] (left product) information. We must caculate the res array through right to left!!!!
Solution:
Public classSolution { Public int[] Productexceptself (int[] nums) { if(Nums = =NULL) Throw NewIllegalArgumentException ("The passed in reference in null!"); if(Nums.length = = 0) returnNums; intLen =nums.length; int[] res =New int[Len]; res[0] = Nums[0]; // from left to right for(inti = 1; i < Len; i++) Res[i]= nums[i] * res[i-1]; // from right to left for(inti = len-2; I >= 0; i--) Nums[i]= nums[i+1] *Nums[i]; for(inti = len-1; I >= 0; i--) { intleft = ((i = = 0)? 1:res[i-1]); intright = ((i = = len-1)? 1:nums[i+1]); Res[i]= left *Right ; } returnRes; }}
[leetcode#238] Product of Array Except self