C++ with extra element trick and partial_sum()

  • 0

    Some of the error handling can be cleaned up by allowing an extra element at the end of the output array. Also partial_sum() eliminates a manual loop.

        class Solution {
            vector<int> getModifiedArray(int length, vector<vector<int>>& updates)
                // add extra element to ease handling of end point cases
                vector<int> res(length + 1, 0);
                for (const auto& update : updates)
                    auto beg = update[0];
                    auto end = update[1] + 1;
                    auto inc = update[2];
                    end = min(end, length);
                    res[beg] += inc;
                    res[end] -= inc;
                partial_sum(begin(res), end(res), begin(res));
                return res;

Log in to reply

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