307. Range Sum Query - Mutable (Medium)

https://leetcode.com/problems/range-sum-query-mutable/

Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

The update(i, val) function modifies nums by updating the element at index i to val.

Example:

Given nums = [1, 3, 5]

sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8

Note:

  1. The array is only modifiable by the update function.
  2. You may assume the number of calls to update and sumRange function is distributed evenly.

Hints

Solutions

class NumArray {

    int[] nums;
    int[] sum;

    public NumArray(int[] nums) {
        this.nums = nums;
        int n = nums.length;
        sum = new int[n + 1];
        for (int i = 0; i < n; i++) {
            sum[i + 1] = sum[i] + nums[i];
        }
    }

    public void update(int i, int val) {
        int delta = val - nums[i];
        for (int j = i; j < nums.length; j++) {
            sum[j + 1] += delta;
        }
        nums[i] = val;
    }

    public int sumRange(int i, int j) {
        return sum[j + 1] - sum[i];
    }
}


/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * obj.update(i,val);
 * int param_2 = obj.sumRange(i,j);
 */
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-15 19:09:31

results matching ""

    No results matching ""