Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.
Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.
Example:
Given nums = [-2, 5, -1], lower = -2, upper = 2,
Return 3.
The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2.
classSolution(object):defcountRangeSum(self,nums,lower,upper):""" :type nums: List[int] :type lower: int :type upper: int :rtype: int """sums=nums[:]forxinrange(1,len(sums)):sums[x]+=sums[x-1]# 排序osums=sorted(set(sums))ft=FenwickTree(len(osums))ans=0forsumiinsums:left=bisect.bisect_left(osums,sumi-upper)right=bisect.bisect_right(osums,sumi-lower)ans+=ft.sum(right)-ft.sum(left)+(lower<=sumi<=upper)ft.add(bisect.bisect_right(osums,sumi),1)returnansclassFenwickTree(object):def__init__(self,n):# 数组的长度self.n=nself.sums=[0]*(n+1)defadd(self,x,val):whilex<=self.n:self.sums[x]+=valx+=self.lowbit(x)deflowbit(self,x):returnx&-xdefsum(self,x):res=0whilex>0:res+=self.sums[x]x-=self.lowbit(x)returnres