LeetCode 238 计算数组除自己外的元素乘积

class Solution {
public:
    vector productExceptSelf(vector& nums) {
        int n = nums.size();
        vector res(n, 1); // res有n个元素,值为1
        if(n <= 1){
            return nums;
        }
        for(int i = 1; i < n; i++){ // res={1, n0, n0n1, n0n1n2};
            res[i] = res[i-1] * nums[i-1];
        }
        int right = 1;
        for(int i = n-2; i >= 0; i--){
            right *= nums[i+1]; // right = n3,n3n2,n3n2n1
            res[i] = res[i]*right;
        }
        return res;
    }
};

你可能感兴趣的:(Leetcode)