Java easy-to-read solution with O(k + n) time and O(1) space.


  • 1
    M
    public int[] getModifiedArray(int length, int[][] updates) {
        int[] ans = new int[length];
        // Iterate updates and use answer array to store two-end info.
        for (int[] update : updates) {
            int l_pos = update[0];
            int r_pos = update[1];
            ans[l_pos] += update[2];
            // Keep update in the range by removing the increment after.
            if (r_pos < length - 1) {
                // Ignore the rightmost update.
                ans[r_pos + 1] -= update[2];
            }
        }
        int sum = 0;
        for (int i = 0; i < length; i++) {
            sum += ans[i];
            ans[i] = sum;
        }
        return ans;
    }

Log in to reply
 

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