238. Product of Array Except Self

来源:互联网 发布:新西兰林肯大学 知乎 编辑:程序博客网 时间:2024/06/10 20:16

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> front(n);        vector<int> back(n);        front[0]=1;        back[n-1]=1;        for(int i=1;i<n;i++){            front[i]=front[i-1]*nums[i-1];            back[n-1-i]=back[(n-1-i)+1]*nums[(n-1-i)+1];        }        //vector<int> res;报错,由于后面直接调用res[i],而这里并没有声明长度        vector<int> res(n);        for(int i=0;i<n;i++){            res[i]=front[i]*back[i];                    }        return res;    }};