Java 7 lines O(K + N) solution with explaination


  • 0
    A
    public int[] getModifiedArray(int length, int[][] updates) {
            int[] res = new int[length];
            for(int[] u : updates) {
                res[u[0]] += u[2];
                if(u[1] != length - 1) res[u[1] + 1] -=  u[2];
            }
            for(int i = 0; i < length - 1; i++) res[i + 1] += res[i];
            return res;
        }
    
    explain: as we add u[2] at start index, when we do res[i + 1] += res[i]; every number after index start will add u[2], so start from end + 1, we need to minus the same number to cancel the effect.

Log in to reply
 

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