1. 程式人生 > >238. Product of Array Except Self (後兩種方法有待進一步研究)

238. Product of Array Except Self (後兩種方法有待進一步研究)

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].
方法一、

vector<int> productExceptSelf(vector
<int>
& nums) { int len = nums.size(); vector<int> left,right(len),ret(len); left.push_back(1); for(int i=1; i<len; i++){ left.push_back(left[i-1]*nums[i-1]); } right[len-1]=1; for(int i=len-2; i>=0; i--){ right[i]=right[i+1
]*nums[i+1]; } for(int i=0; i<len; i++){ ret[i]=left[i]*right[i]; } return ret; }

方法二、O(n) time and O(n) space solution.

vector<int> productExceptSelf(vector<int>& nums) {
        int n=nums.size();
        vector<int> fromBegin(n);
        fromBegin[0
]=1; vector<int> fromLast(n); fromLast[0]=1; for(int i=1;i<n;i++){ fromBegin[i]=fromBegin[i-1]*nums[i-1]; fromLast[i]=fromLast[i-1]*nums[n-i]; } vector<int> res(n); for(int i=0;i<n;i++){ res[i]=fromBegin[i]*fromLast[n-1-i]; } return res; }

方法三、

vector<int> productExceptSelf(vector<int>& nums) {
        int n=nums.size();
        int fromBegin=1;
        int fromLast=1;
        vector<int> res(n,1);

        for(int i=0;i<n;i++){
            res[i]*=fromBegin;
            fromBegin*=nums[i];
            res[n-1-i]*=fromLast;
            fromLast*=nums[n-1-i];
        }
        return res;
    }