370. Range Addition

Assume you have an array of lengthninitialized with all0's and are givenkupdate operations.

Each operation is represented as a triplet:[startIndex, endIndex, inc]which increments each element of subarrayA[startIndex ... endIndex](startIndex and endIndex inclusive) withinc.

Return the modified array after allkoperations were executed.

Example:

Given:

    length = 5,
    updates = [
        [1,  3,  2],
        [2,  4,  3],
        [0,  2, -2]
    ]

Output:

    [-2, 0, 3, 5, 3]

Explanation:

Initial state:
[ 0, 0, 0, 0, 0 ]

After applying operation [1, 3, 2]:
[ 0, 2, 2, 2, 0 ]

After applying operation [2, 4, 3]:
[ 0, 2, 5, 5, 3 ]

After applying operation [0, 2, -2]:
[-2, 0, 3, 5, 3 ]

Credits:
Special thanks to@vinod23for adding this problem and creating all test cases.

class Solution {
    public int[] getModifiedArray(int length, int[][] updates) {

        Map<Integer, Integer> hash = new HashMap<>();
        for (int[] up : updates){
            hash.put(up[0], hash.getOrDefault(up[0], 0) + up[2]);
            hash.put(up[1] + 1, hash.getOrDefault(up[1] + 1, 0) - up[2]);
        }

        int[] ans = new int[length];
        int sum = 0;
        for (int i = 0; i < length; i++){
            sum += hash.getOrDefault(i, 0);
            ans[i] = sum;
        }

        return ans;
    }
}

results for ""

    No results matching ""