代码拉取完成,页面将自动刷新
/*
* @lc app=leetcode.cn id=327 lang=cpp
*
* [327] 区间和的个数
*/
// @lc code=start
class Solution {
private:
vector<long> temp;
vector<long> preSum;
int count = 0;
int lower, upper;
void sort(vector<long>& nums, int lo, int hi) {
if (lo >= hi) return;
int mid = lo + (hi - lo) / 2;
sort(nums, lo, mid);
sort(nums, mid + 1, hi);
merge(nums, lo, mid, hi);
}
void merge(vector<long>& nums, int lo, int mid, int hi) {
for (int i = lo; i <= hi; i++) {
temp[i] = nums[i];
}
int start = mid + 1, end = mid + 1;
for (int i = lo; i < mid + 1; i++) {
while (start <= hi && nums[start] - nums[i] < lower) {
start++;
}
while (end <= hi && nums[end] - nums[i] <= upper) {
end++;
}
count += end - start;
}
int i = lo, j = mid + 1;
for (int p = lo; p <= hi; p++) {
if (i == mid + 1) {
nums[p] = temp[j++];
} else if (j == hi + 1) {
nums[p] = temp[i++];
} else if (temp[i] > temp[j]) {
nums[p] = temp[j++];
} else {
nums[p] = temp[i++];
}
}
}
public:
int countRangeSum(vector<int>& nums, int lower, int upper) {
this->lower = lower;
this->upper = upper;
preSum.resize(nums.size() + 1, 0);
for (int i = 0; i < nums.size(); i++) {
preSum[i+1] = (long)nums[i] + preSum[i];
}
temp.resize(preSum.size(), 0);
sort(preSum, 0, preSum.size() - 1);
return count;
}
};
// @lc code=end
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。