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;
    };
  • 相关阅读:
    Scala编译环境搭建(mac IDEA)
    Scala初见
    boost spirit使用
    基于OPENCV的图像融合
    C++获取hostname&IP&MAC地址
    httpd启动检查
    react eslint 代码格式补全的插件
    将html页面导出为word
    redux的笔记
    img onerror事件的使用
  • 原文地址:https://www.cnblogs.com/shytong/p/5114708.html
Copyright © 2011-2022 走看看