题目:

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;
};

 

相关文章:

  • 2021-10-03
  • 2021-10-05
  • 2021-10-08
  • 2021-12-19
猜你喜欢
  • 2021-11-30
  • 2021-11-20
  • 2021-06-21
  • 2021-08-28
相关资源
相似解决方案