提交 f3d4f5ea 编写于 作者: jhaos's avatar jhaos

Add new file

上级 e85f503b
给定一个整数数组 `nums`,返回区间和在` [lower, upper] `之间的个数,包含 `lower``upper`
区间和 `S(i, j) `表示在` nums `中,位置从 `i`` j `的元素之和,包含` i ``j (i ≤ j)`
**说明:**
最直观的算法复杂度是 `O(n2) `,请在此基础上优化你的算法。
**示例:**
```
输入: nums = [-2,5,-1], lower = -2, upper = 2,
输出: 3
解释: 3个区间分别是: [0,0], [2,2], [0,2],它们表示的和分别为: -2, -1, 2。
```
通过次数`8,041` | 提交次数`21,427`
**代码实现**
```python
class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
import bisect
t = [0]
for n in nums:
t.append(t[-1]+n)
l = len(t)
re=0
asc = []
for x in t:
i = bisect.bisect_left(asc, x- upper)
j = bisect.bisect(asc, x- lower)
bisect.insort(asc, x)
re += j - i
return re
```
```
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-of-range-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册