【数组】Product of Array Except Self
题目:
iven an array of n integers where n > 1, nums
, return an array output
such that output[i]
is equal to the 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 you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
思路:
这道题只要将nums中乘积求出来,然后将乘积除以nums中每一项(nums[i])即可。但要注意0的情况。
/** * @param {number[]} nums * @return {number[]} */ var productExceptSelf = function(nums) { var pro=1,res=[],flag=0; for(var i=0,len=nums.length;i<len;i++){ if(nums[i]==0){ flag++; }else{ pro*=nums[i]; } } for(var i=0,len=nums.length;i<len;i++){ if(nums[i]!=0&&flag){ res[i]=0; }else if(nums[i]!=0&&flag==0){ res[i]=pro/nums[i] }else if(nums[i]==0&&flag==1){ res[i]=pro; }else if(nums[i]==0&&flag>1){ res[i]=0; } } return res; };