Leetcode 每日一题
题目链接: 327. 区间和的个数
难度: 困难
解题思路: 今天有急事,来不及做了。大概看了一下,区间问题,要求时间复杂度小于O(n*n)。很容易想到用线段树或者树状数组,搬运Leetcode 官方题解。
题解:
struct SegNode {
int lo, hi, add;
SegNode* lchild, *rchild;
SegNode(int left, int right): lo(left), hi(right), add(0), lchild(nullptr), rchild(nullptr) {}
};
class Solution {
public:
SegNode* build(int left, int right) {
SegNode* node = new SegNode(left, right);
if (left == right) {
return node;
}
int mid = (left + right) / 2;
node->lchild = build(left, mid);
node->rchild = build(mid + 1, right);
return node;
}
void insert(SegNode* root, int val) {
root->add++;
if (root->lo == root->hi) {
return;
}
int mid = (root->lo + root->hi) / 2;
if (val <= mid) {
insert(root->lchild, val);
}
else {
insert(root->rchild, val);
}
}
int count(SegNode* root, int left, int right) const {
if (left > root->hi || right < root->lo) {
return 0;
}
if (left <= root->lo && root->hi <= right) {
return root->add;
}
return count(root->lchild, left, right) + count(root->rchild, left, right);
}
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++;
}
SegNode* root = build(0, values.size() - 1);
int ret = 0;
for (long long x: preSum) {
int left = values[x - upper], right = values[x - lower];
ret += count(root, left, right);
insert(root, values[x]);
}
return ret;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/count-of-range-sum/solution/qu-jian-he-de-ge-shu-by-leetcode-solution/
来源:力扣(LeetCode)