Concise 60ms C++ solution with one vector


  • 2
    D

    First we accumulate the product from the left, storing the intermediate results. Then we accumulate the product from the right, multiplying the intermediate results with the stored left results.

    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            vector<int> result (nums.size(), 1);
            int left = 1, right = 1;
            for (int i = 1; i < nums.size(); ++i) {
                left *= nums[i - 1], result[i] *= left;
            }
            for (int i = nums.size() - 2; i >= 0; --i) {
                right *= nums[i + 1], result[i] *= right;
            }
            return result;
        }
    };

Log in to reply
 

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