A Simple C++ Solution with O(n) time and O(1) space.


  • 0
    B
     vector<int> productExceptSelf(vector<int>& nums) {
            int n = nums.size();
            vector<int> output = nums;
            if(n <= 1) return output;
            for(int i = 1; i < n-1; i++)
            {
                output[i] = output[i] * output[i - 1];
            }
            output[n - 1] = output[n - 2];
            for(int i = n - 2; i >= 1; i--)
            {
                output[i] = output[i - 1]*nums[i + 1];
                nums[i] *= nums[i + 1];
            }
            output[0] = nums[1];
            return output;
        }
    

Log in to reply
 

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