1 Star 0 Fork 1

陈鹏/leecode with labuladong

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
327.区间和的个数.cpp 1.69 KB
一键复制 编辑 原始数据 按行查看 历史
陈鹏 提交于 2022-07-14 18:54 . 二叉树序列化、归并排序
/*
* @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
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Chan1998/leecode-with-labuladong.git
git@gitee.com:Chan1998/leecode-with-labuladong.git
Chan1998
leecode-with-labuladong
leecode with labuladong
master

搜索帮助