难度: Medium
原题连接
内容描述
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:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
思路 1 - 时间复杂度: update O(lgN) + sumRange O(lgN)- 空间复杂度: O(N)******
直接segment tree
class NumArray:
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.n = len(nums)
self.tree = [0] * (2 * self.n)
def buildTree(nums):
self.tree[self.n:] = nums[:]
for i in range(self.n-1, 0, -1):
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
buildTree(nums)
def update(self, i, val):
"""
:type i: int
:type val: int
:rtype: void
"""
i += self.n
self.tree[i] = val
while i > 0:
self.tree[i // 2] = self.tree[i // 2 * 2] + self.tree[i // 2 * 2 + 1]
i //= 2
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
i, j = i + self.n, j + self.n
sums = 0
while i <= j:
if i % 2 == 1: # 左边多出一个不能成对的
sums += self.tree[i]
i += 1
if j % 2 == 0: # 右边多出一个不能成对的
sums += self.tree[j]
j -= 1
i //= 2
j //= 2
return sums