美文网首页
**238 Product of Array Except S

**238 Product of Array Except S

作者: Mree111 | 来源:发表于2019-04-20 15:21 被阅读0次

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]

Solution

[1,a1,a1a2,.....,a1a2..an-1]
[a2
a3...an,an*an-1,an,1]相乘即可
divide the multiplying process into two passes.

        
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int left=1;
        int right=1;
        int[] res=new int[nums.length];
        for(int i=0;i<nums.length;i++){
            res[i]=left;
            left*=nums[i];
        }
        for(int i=nums.length-1;i>=0;i--){
            res[i]*=right;
            right*=nums[i];
        }
        return res;
    }
}

相关文章

网友评论

      本文标题:**238 Product of Array Except S

      本文链接:https://www.haomeiwen.com/subject/omcfgqtx.html