-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path307.Range-Sum-Query-Mutable.py
67 lines (53 loc) · 1.41 KB
/
307.Range-Sum-Query-Mutable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# https://leetcode.com/problems/range-sum-query-mutable/
#
# algorithms
# Medium (27.45%)
# Total Accepted: 65,574
# Total Submissions: 238,851
# beats 100.0% of python submissions
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
length = len(nums)
tree_arr = [0] * (length + 1)
for i in xrange(1, length + 1):
tree_arr[i] = nums[i - 1]
for i in xrange(1, length + 1):
j = i + (i & -i)
if j <= length:
tree_arr[j] += tree_arr[i]
self.tree_arr = tree_arr
self.nums = nums
def update(self, i, val):
"""
:type i: int
:type val: int
:rtype: void
"""
delta = val - self.nums[i]
self.nums[i] = val
length = len(self.tree_arr)
i += 1
while i < length:
self.tree_arr[i] += delta
i = i + (i & -i)
def prefixSum(self, i):
i += 1
res = 0
while i > 0:
res += self.tree_arr[i]
i = i - (i & -i)
return res
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return self.prefixSum(j) - self.prefixSum(i - 1)
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# obj.update(i,val)
# param_2 = obj.sumRange(i,j)