zoukankan      html  css  js  c++  java
  • 52.Product of Array Except Self(除过自身的数组乘积)

    Level:

      Medium

    题目描述:

    Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

    Example:

    Input:  [1,2,3,4]
    Output: [24,12,8,6]
    

    Note: Please solve it without division and in O(n).

    Follow up:
    Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

    思路分析:

      我们可以求出整个数组的乘积allProduct,然后,result[ i ]就为allProduct除以nums[ i ],如果数组中有零,那么除过为零元素对应位置外,其他位置对应结果都为零。

    代码:

    public class Solution{
        public int []productExceptSelf(int[]nums){
            int allProduct=1;
            int[] res=new int[nums.length];
            int flag=0; //标志出现零
            for(int i=0;i<nums.length;i++){
                if(nums[i]==0&&flag==0){
                    flag=1;
                    continue;
                }
                allProduct=allProduct*nums[i];
            }
            for(int i=0;i<res.length;i++){
                if(flag==1){
                    if(nums[i]!=0)
                        res[i]=0;
                    else
                        res[i]=allProduct;
                }else{
                    
                    res[i]=allProduct/nums[i];
                }
            }
            return res;
        }
    }
    

  • 相关阅读:
    CAS简介
    Volatile的3大特性
    dsf对矩阵进行搜索
    JVM
    REST风格
    自定义Starters(自动配置Bean)
    反射和注解的原理
    mybatis的注解开发
    Java的多线程安全
    mybatis(3)
  • 原文地址:https://www.cnblogs.com/yjxyy/p/11088878.html
Copyright © 2011-2022 走看看