C++ Concise code, handles invalid 'updates' cases.


  • 0

    What if startIndex, endIndex are invalid, then we need to do this:

    class Solution {
    public:
        vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
            vector<int> res(length, 0);
            
            for(int i = 0; i < updates.size(); i++){
                if(updates[i][0] >= 0 && updates[i][0] < length) 
                    res[updates[i][0]] += updates[i][2];
                if(updates[i][1] >= 0 && updates[i][1] < length - 1) 
                    res[updates[i][1]+1] -= updates[i][2];
            }
            
            for(int i = 1; i < length; i++)
                res[i] += res[i-1];
            
            return res;
        }
    };
    

Log in to reply
 

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