LeetCode刷题——327.区间和的个数
题目描述
给你一个整数数组 nums 以及两个整数 lower 和 upper 。求数组中,值位于范围 [lower, upper] (包含 lower 和 upper)之内的 区间和的个数 。
区间和 S(i, j) 表示在 nums 中,位置从 i 到 j 的元素之和,包含 i 和 j (i ≤ j)。
来源:力扣(LeetCode)
一、前缀和+二分法
首先使用简单的计算所有区间和进行判断会超时,时间复杂度为
O
(
n
2
)
O(n^2)
O(n2)。
学习的第一种办法为前缀和+二分法。
预备知识:bisect
是python内置的数组二分查找算法(官方解释)
本次使用三个方法:
bisect.bisect_left(array,x) #查询在数组array中按照顺序在元素相同时向左插入x的位置的应该插入的位置,即找出比x小等于的元素所在位置。
bisect.bisect_right(array,x) #查询在数组array中按照顺序在元素相同时向右插入x的位置
上面两个函数返回结果用以计算满足条件的区间和的个数,搜索时间复杂度为
O
(
l
o
g
(
n
)
)
O(log(n))
O(log(n))
bisect.insect(array,x)将x插入到array中x的左侧,时间复杂度为
O
(
n
)
O(n)
O(n)
主要的优化思想为,区间和 S [ i , j ] = p r e [ j ] − p r e [ i ] S[i,j]=pre[j]-pre[i] S[i,j]=pre[j]−pre[i]。在计算 p r e [ i ] ∈ [ p r e [ j ] − u p p e r , p r e [ j ] − l o w e r ] pre[i] \in [pre[j]-upper,pre[j]-lower] pre[i]∈[pre[j]−upper,pre[j]−lower] 即可。使用二分法找出上述区间所在的位置, c o u n t + = r − l count+=r-l count+=r−l。注意一定要使用insert把 p r e [ j ] pre[j] pre[j]加景区保证数组的顺序。由于是查完了再加,则当前array里面所有的前缀和都在 p r e [ j ] pre[j] pre[j]的前面。
class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
pre=[0]
temp=0
l=len(nums)
count=0
for i in range(l):
temp+=nums[i]
r=bisect.bisect_right(pre,temp-lower)
l=bisect.bisect_left(pre,temp-upper)
count+=r-l
#pre.append(temp)
bisect.insort(pre,temp)
#print(pre)
return count
总结
这个方法能过但是速度还是比较慢,虽然调用了内置函数。搜索两次时间复杂度为 O ( l o g ( n ) ) O(log(n)) O(log(n)),插入一次时间复杂度为 O ( n ) O(n) O(n)。遍历数组的时间复杂度为 O ( n ) O(n) O(n)。其实差不多能有 O ( n 2 ) O(n^2) O(n2)了,属于勉强过。