这个题目怎么去想呢,我们先构造前缀和,一般思路肯定是用两层循环,但是一定会超时,我们的数据范围是 1e5,那我们必须找到复杂度为 nlog n 的才行,所以我们可以考虑每次计算以 i 结尾的子数组的数量,我们只要计算 i 之前的前缀和在 d[i] - upper 和 d[i] - lower 之间的数量,这就需要我们离散化我们的数据
class BIT {
private:vector<int> tree;int n;public:BIT(int _n): n(_n), tree(_n + 1) {}static constexpr int lowbit(int x) {return x & (-x);}void update(int x, int d) {while (x <= n) {tree[x] += d;x += lowbit(x);}}int query(int x) const {int ans = 0;while (x) {ans += tree[x];x -= lowbit(x);}return ans;}
};class Solution {
public:int countRangeSum(vector<int>& nums, int lower, int upper) {long long sum = 0;vector<long long> preSum = {0};for (int v: nums) {sum += v;preSum.push_back(sum);}set<long long> allNumbers;for (long long x: preSum) {allNumbers.insert(x);allNumbers.insert(x - lower);allNumbers.insert(x - upper);}// 利用哈希表进行离散化unordered_map<long long, int> values;int idx = 0;for (long long x: allNumbers) {values[x] = idx;idx++;}int ret = 0;BIT bit(values.size());for (int i = 0; i < preSum.size(); i++) {int left = values[preSum[i] - upper], right = values[preSum[i] - lower];ret += bit.query(right + 1) - bit.query(left);bit.update(values[preSum[i]] + 1, 1);}return ret;}
};