Solution in c++


  • 0
    J
    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            int n = nums.size();
            vector<int> ret(n);
            ret[n - 1] = nums[n - 1];
            for (int i = n - 2; i >= 0; i--)          // postfix product
                ret[i] = ret[i + 1] * nums[i];
            for (int i = 1; i < n; i++)               // prefix product
                nums[i] = nums[i - 1] * nums[i];
            ret[0] = ret[1];                          
            for (int i = 1; i < n - 1; i++)           // get the result
                ret[i] = nums[i - 1] * ret[i + 1];
            ret[n - 1] = nums[n - 2];
            return ret;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.