-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0327-count-of-range-sum.py
More file actions
77 lines (60 loc) · 2.13 KB
/
0327-count-of-range-sum.py
File metadata and controls
77 lines (60 loc) · 2.13 KB
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
68
69
70
71
72
73
74
75
76
77
# time complexity: O(nlogn)
# space complexity: O(n)
from typing import List
class SegmentTree:
def __init__(self, size: int):
self.n = size
self.segTree = [0 for _ in range(4 * size)]
def update(self, idx: int, val: int, nodeIdx=0, start=0, end=None):
if end is None:
end = self.n - 1
if start == end:
self.segTree[nodeIdx] += val
return
mid = (start + end) // 2
leftIdx = 2 * nodeIdx + 1
rightIdx = 2 * nodeIdx + 2
if idx <= mid:
self.update(idx, val, leftIdx, start, mid)
else:
self.update(idx, val, rightIdx, mid + 1, end)
self.segTree[nodeIdx] = self.segTree[leftIdx] + self.segTree[rightIdx]
def query(self, left: int, right: int, nodeIdx=0, start=0, end=None) -> int:
if end is None:
end = self.n - 1
if right < start or left > end:
return 0
if left <= start and end <= right:
return self.segTree[nodeIdx]
mid = (start + end) // 2
leftIdx = 2 * nodeIdx + 1
rightIdx = 2 * nodeIdx + 2
return self.query(left, right, leftIdx, start, mid) + self.query(left, right, rightIdx, mid + 1, end)
class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
preSums = [0]
for num in nums:
preSums.append(preSums[-1] + num)
allSums = set()
for preSum in preSums:
allSums.add(preSum)
allSums.add(preSum - lower)
allSums.add(preSum - upper)
sortedSums = sorted(allSums)
rankMap = {val: idx for idx, val in enumerate(sortedSums)}
tree = SegmentTree(len(sortedSums))
count = 0
for preSum in preSums:
left = rankMap[preSum - upper]
right = rankMap[preSum - lower]
count += tree.query(left, right)
tree.update(rankMap[preSum], 1)
return count
nums = [-2, 5, -1]
lower = -2
upper = 2
print(Solution().countRangeSum(nums, lower, upper))
nums = [0]
lower = 0
upper = 0
print(Solution().countRangeSum(nums, lower, upper))