leetcode_238. Product of Array Except Self_思维

https://leetcode.com/problems/product-of-array-except-self/

给一个vector<int> nums,输出一个vector<int> res,res[i]为nums中除去nums[i]以外所有数的乘积。且不能使用除法运算,时间复杂度为O(n),空间复杂度尽量小。

思路:首先从左往右遍历,对任意i,可以求得nums[0,i-1]的乘积;再从右往左遍历,对任意i,可以求得nums[i+1,n-1]的乘积。根据题意,只需要额外需要O(1)的空间复杂度。

class Solution
{
public:
    vector<int> productExceptSelf(vector<int>& nums)
    {
        int len = nums.size();
        vector<int> res = nums;
        res[0]=1;
        cout<<res[0]<<endl;
        for(int i=1; i<len; i++)
            res[i] = res[i-1] * nums[i-1];
        int tmp = 1;
        for(int i=len-1; i>=0; i--)
        {
            res[i] = res[i]*tmp;
            tmp *= nums[i];
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/jasonlixuetao/p/10088848.html