Range Sum Query - Mutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), 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.

这题是 Rqnge Sum Query - Immutable 的follow up。因为需要update 数据,使用 prefix sum array 的办法就比较慢了。使用 binary indexed tree 或者 segementation tree 比较好。使用 binary indexed tree:

class NumArray(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.nums = [0] * len(nums)
        self.BIT = [0] * (len(nums) + 1)
        for i, n in enumerate(nums):
            self.update(i, n)


    def update(self, i, val):
        """
        :type i: int
        :type val: int
        :rtype: void
        """
        delta = val - self.nums[i]
        self.nums[i] = val
        i += 1
        while i < len(self.BIT):
            self.BIT[i] += delta
            i += i & (-i)


    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        return self.getSum(j) - self.getSum(i - 1)


    def getSum(self, i):
        i += 1
        ans = 0
        while i > 0:
            ans += self.BIT[i]
            i -= i & (-i)
        return ans


# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# obj.update(i,val)
# param_2 = obj.sumRange(i,j)

Last updated

Was this helpful?