Binary Indexed Tree
class NumArray(object):
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
if not nums:
return
self.__nums = nums
self.__bit = [0] * (len(self.__nums) + 1)
#calculate prefix sum array
for i in xrange(1, len(self.__bit)):
self.__bit[i] = nums[i-1] + self.__bit[i-1]
#every bit array element store the sum of n number of elements, where n=low bit value
#for example bit[7]=bit[111],low bit of 111= 1, bit[7] store the sum of one element counting back from 7 which is nums[6]
#for example bit[12]=bit[1100],low bit of 1100=4, bit[12] store the sum of four elements counting back from 12 whic is nums[8~11]
#bit[i] stores low_bit_of_i elements= nums[i-low_bit_of_i]+..+nums[i-1]=prefixsum[i]-prefixsum[i-low_bit_of_i]
for i in reversed(xrange(1, len(self.__bit))):
last_i = i - (i & -i)
self.__bit[i] -= self.__bit[last_i]
def update(self, i, val):
"""
:type i: int
:type val: int
:rtype: int
"""
if val - self.__nums[i]:
self.__add(i, val - self.__nums[i])
self.__nums[i] = val
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
return self.__sum(j) - self.__sum(i-1)
def __sum(self, i):
i += 1
ret = 0
while i > 0:
ret += self.__bit[i]
i -= (i & -i)
return ret
def __add(self, i, val):
i += 1
while i <= len(self.__nums):
self.__bit[i] += val
i += (i & -i)
307. Range Sum Query - Mutable
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Question Given an integer array nums, find the sum of the...
- Given an integer array nums, find the sum of the elements...
- two sum 3 sum 3Sum Closest 4 sum 利用set来实现: 3 sum 4 sum
- Range Sum Query - Immutable给定一个数组,指定两个indices之间(inclusive...