Clean c++ solution


  • 0
    1. initialize result to be length + 1, for easy update.
    2. increase element with startIndex by val.
    3. decrease element with endIndex + 1 by val.
    4. update each element i > 0 to be element i + element i - 1
    vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
            vector<int> result(length + 1, 0);
            for (auto update : updates) {
                result[update[0]] += update[2];
                result[update[1] + 1] -= update[2];
            }
            for (int i = 1; i < length; i++) {
                result[i] += result[i - 1];
            }
            result.resize(length);
            return result;
        }
    

Log in to reply
 

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