238. Product of Array Except Self

来源:互联网 发布:java svn资源库导出去 编辑:程序博客网 时间:2024/05/20 22:39
题面:

Given 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.)

题解:由于不能用除法,自然会想到当遍历到某一个数时,将其左边依次相乘,在将其右边依次相乘,即可。所以用两个数组记录。

代码:

class Solution {public:    vector<int> productExceptSelf(vector<int>& nums) {        int n=nums.size();        vector<int> a(n);        vector<int> b(n);        a[0]=1;        b[0]=1;        vector<int> res(n);        for(int i=1;i<n;i++){            a[i]=a[i-1]*nums[i-1];            b[i]=b[i-1]*nums[n-i];        }        for(int i=0;i<n;i++){            res[i]=a[i]*b[n-i-1];    }    return res;    }};