Skip to content

Commit a4ff867

Browse files
committed
[LeetCode Sync] Runtime - 1701 ms (22.25%), Memory - 52.4 MB (38.67%)
1 parent e4de5fb commit a4ff867

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<p>Given an integer array <code>nums</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of range sums that lie in</em> <code>[lower, upper]</code> <em>inclusive</em>.</p>
2+
3+
<p>Range sum <code>S(i, j)</code> is defined as the sum of the elements in <code>nums</code> between indices <code>i</code> and <code>j</code> inclusive, where <code>i &lt;= j</code>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> nums = [-2,5,-1], lower = -2, upper = 2
10+
<strong>Output:</strong> 3
11+
<strong>Explanation:</strong> The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> nums = [0], lower = 0, upper = 0
18+
<strong>Output:</strong> 1
19+
</pre>
20+
21+
<p>&nbsp;</p>
22+
<p><strong>Constraints:</strong></p>
23+
24+
<ul>
25+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
26+
<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>
27+
<li><code>-10<sup>5</sup> &lt;= lower &lt;= upper &lt;= 10<sup>5</sup></code></li>
28+
<li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li>
29+
</ul>
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
3+
n = list(accumulate(nums, initial=0))
4+
sorted_array = sorted(set(val for x in n for val in (x, x - lower, x - upper)))
5+
tree = BinaryIndexedTree(len(sorted_array))
6+
result = 0
7+
8+
for x in n:
9+
left = bisect_left(sorted_array, x - upper) + 1
10+
right = bisect_left(sorted_array, x - lower) + 1
11+
result += tree.query(right) - tree.query(left - 1)
12+
tree.update(bisect_left(sorted_array, x) + 1, 1)
13+
14+
return result
15+
16+
class BinaryIndexedTree:
17+
def __init__(self, n):
18+
self.n = n
19+
self.tree = [0] * (n + 1)
20+
21+
def update(self, x, v):
22+
while x <= self.n:
23+
self.tree[x] += v
24+
x += x & -x
25+
26+
def query(self, x):
27+
result = 0
28+
while x > 0:
29+
result += self.tree[x]
30+
x -= x & -x
31+
return result

0 commit comments

Comments
 (0)