Share my C++ solution by using partial_sum and transform


  • 0
    G
    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            vector<int> products(1, 1);
            partial_sum(nums.begin(), nums.end() - 1, back_inserter(products), multiplies<int>());
            partial_sum(nums.rbegin(), nums.rend() - 1, nums.rbegin(), multiplies<int>());
            transform(products.begin(), products.end() - 1, nums.begin() + 1, products.begin(), multiplies<int>());
            return products;
        }
    };
    

    No extra space if the output and input vectors do not count, but the input vector got transformed, which somehow should be considered as extra space. However, I just try to share a solution by using STL functions.


Log in to reply
 

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