zoukankan      html  css  js  c++  java
  • 【数组】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;
    };
  • 相关阅读:
    数据库优化
    List,map,Set区别
    ID选择器
    最简单的添加删除行操作
    JQ2
    最简单的JQ实现
    20180416
    一行细分的HTML写法
    out参数的使用
    结构的使用
  • 原文地址:https://www.cnblogs.com/shytong/p/5114708.html
Copyright © 2011-2022 走看看