forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
30 lines (26 loc) · 852 Bytes
/
Solution.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
class BinaryIndexedTree:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
def update(self, x, v):
while x <= self.n:
self.c[x] += v
x += x & -x
def query(self, x):
s = 0
while x > 0:
s += self.c[x]
x -= x & -x
return s
class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
s = list(accumulate(nums, initial=0))
arr = sorted(set(v for x in s for v in (x, x - lower, x - upper)))
tree = BinaryIndexedTree(len(arr))
ans = 0
for x in s:
l = bisect_left(arr, x - upper) + 1
r = bisect_left(arr, x - lower) + 1
ans += tree.query(r) - tree.query(l - 1)
tree.update(bisect_left(arr, x) + 1, 1)
return ans