lleetcode 307. Range Sum Query

来源:互联网 发布:网络市场调查问卷 编辑:程序博客网 时间:2024/06/07 11:11

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) -> 9update(1, 2)sumRange(0, 2) -> 8

Note:

  1. The array is only modifiable by the update function.

  1. You may assume the number of calls to update and sumRange function is distributed evenly.

class NumArray(object):    def __init__(self, nums):        self.n = len(nums)        self.c = [0] * (self.n+1)        self.nums = [0] * (self.n+1)        for i in range(0 , self.n):            self.update(i , nums[i])    def lowbit(self , x):        return x & (-x)    def update(self, i, val):        dif = val - self.nums[i]        self.nums[i] = val        i += 1        while i <= self.n:            self.c[i] += dif            i += self.lowbit(i)    def sumPrefix(self , i):        sum = 0        i += 1        while i > 0 :            sum += self.c[i]            i -= self.lowbit(i)        return sum    def sumRange(self, i, j):        return self.sumPrefix(j) - self.sumPrefix(i-1)if __name__ == '__main__':    obj = NumArray([1, 3, 5])    print(obj.sumRange(0 , 2))    obj.update(1 , 2)    print(obj.sumRange(0, 2))