leecode第二百三十八题(除自身以外数组的乘积)

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int len=nums.size();
        vector<int> res;
        
        for(int i=0,temp=1;i<len;i++)//把前面的乘起来,暂存起来
        {
            res.push_back(temp);
            temp=temp*nums[i];
        }
        
        for(int i=len-1,temp=1;i>=0;i--)//倒着再乘一遍,刚好错开自己位置的数值
        {
            res[i]=res[i]*temp;
            temp=temp*nums[i];
        }
        return res;
    }
};

分析:

不给说O(n)时间复杂度,O(1)空间复杂度,我还真想不到这么好的。

猜你喜欢

转载自www.cnblogs.com/CJT-blog/p/10724324.html