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

posted @ 2019-06-26 11:25  yjxyy  阅读(104)  评论(0)    收藏  举报