我正在解决一个问题。
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
我的解决方案如下:
1.将[0,i]中的所有总和作为sum[i]
2.将sum向量排序为克隆向量,并根据其在克隆向量中的索引重新索引sum中的元素。将 sum 元素值作为映射反映的键,将新索引作为反映的值。将向量和元素从后到前添加到二叉索引树中,同时在clone中找到满足上下限条件的有效元素索引范围[idx1,idx2]。
3.在我们的BIT中得到从节点0到节点idx1的总和以及从节点0到节点idx2的总和。如果节点已经插入到 BIT 中,我们将在 BIT 中找到该节点。所以满足我们绑定条件的节点数量就是总和。
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;
}
错误:输入:[-2,5,-1] -2 2 输出:197 预期:3
而且我真的不知道如何格式化我的代码,我总是这样写 c++..
对不起,它有点长,我想了几天仍然不知道哪里出了问题。任何想法表示赞赏!