最近写了好多分治算法的题目啊,总结如下就是找出数组第i位后面的某些符合条件的位的个数,这一类型都可以用sort&merge做出来(当然也可以用bst,因为这都是存在插入顺序,刚好可以用来筛选是否为第i位后面一位),当然这一题还有很多解法,譬如二叉树。用sum建树,然后在add的时候比较。
class Solution {
public:
int mergeSort(vector<int>& nums, int lower, int upper) {
int sum = 0;
int n = (int)nums.size();
if(n < 1) return 0;
else if(n == 1){
if(nums[0] <= upper && nums[0] >= lower) return 1;
else return 0;
}
vector<int> a(nums.begin(), nums.begin() + n/2);
vector<int> b(nums.begin() + n/2, nums.end());
sum += mergeSort(a, lower, upper);
sum += mergeSort(b, lower, upper);
int an = 0, bn = 0;
int fi = 0, la = 0;
for(int i = 0; i<a.size(); i++){
while(fi != b.size() && a[i] + lower > b[fi]) fi++;
la = fi;
while(la != b.size() && a[i] + upper >= b[la]) la++;
sum += la - fi;
}
for(int i = 0; i<n; i++){
if(bn == b.size() || (an < a.size() && a[an] <= b[bn])) nums[i] = a[an++];
else{
nums[i] = b[bn++];
}
}
return sum;
}
int countRangeSum(vector<int>& nums, int lower, int upper) {
int n = (int)nums.size();
vector<int> sum(n, 0);
sum[0] = nums[0];
for(int i = 1; i<n; i++) sum[i] = nums[i] + sum[i-1];
return mergeSort(sum, lower, upper);
}
};