I am solving a problem.
Count of Range Sum
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.
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
My solution is below:
1.get all sums from[0,i] as sum[i]
2.sort sum vector as clone vector, and reindex elements in sum according to its index in clone vector. Put sum element value as map reflect's key, new index as reflect's value. add vector sum element from back to front into Binary Indexed Tree, and at the same time find valid elements index range [idx1,idx2] in clone which satisfies the lowerbound and upperbound condition.
3.get the sum from node 0 to node idx1 and sum from node 0 to node idx2 in our BIT. If the node is inserted into the BIT already we will find the node in our BIT. So the node amount which satisfies our bound conditifon is the sum.
public:
vector<long>tree,clone;
int countRangeSum(vector<int>& nums, int lower, int upper) {
int n=nums.size();
vector<long>sum(n+1);
for(int i=1;i<=n;i++)
sum[i]=sum[i-1]+nums[i-1];// step1
clone=sum;
sort(clone.begin(),clone.end());
tree.resize(sum.size()+1);
unordered_map<long,int>reflect;
for(int i=0;i<clone.size();i++)
reflect[clone[i]]=i;//step2
int res=0;
for(int i=sum.size()-1;i>=0;i--)
{
int idx1=binarysearch(sum[i]+lower,true);
int idx2=binarysearch(sum[i]+upper,false);
res=res+count(idx2)-count(idx1);
add(reflect[sum[i]]); //step3
}
return res;
}
int binarysearch(long val, bool includeself)
{
if(includeself)
return lower_bound(clone.begin(),clone.end(),val)-clone.begin();
return upper_bound(clone.begin(),clone.end(),val)-clone.begin();
}
void add(int pos){
pos=pos+1;
while(pos<tree.size())
{
tree[pos]++;
pos=pos+(pos&-pos);
}
}
int count(int pos){
int cnt=0;
pos=pos+1;
while(pos>0)
{
cnt=cnt+tree[pos];
pos=pos-(pos&-pos);
}
return cnt;
}
Errors: Input: [-2,5,-1] -2 2 Output: 197 Expected: 3
And I don't really know how to format my code, I always wrote c++ like this so..
Sorry it gets a bit long, I thought it for several days still no clue where goes wrong. Any thought is appreciated!!