题目:307
题意:给定一个整数数组,可以随时对某一数组元素值进行修改,设计一个算法求任意范围内数值和
题解:线段树
线段树是一种非常灵活的数据结构,它可以用于解决多种范围查询问题,比如在对数时间内从数组中找到最小值、最大值、总和、最大公约数、最小公倍数等。
线段树可以分为以下三个步骤:
- 从给定数组构建线段树的预处理步骤。
- 修改元素时更新线段树。
- 使用线段树进行区域和检索。
代码:
class NumArray {
private:
int * t;
int n;
public:
NumArray(vector<int>& nums) {
n = nums.size();
//构建线段树
t = new int[2 * n];
for (int i = n; i < 2 * n; ++i)
t[i] = nums[i - n];
for (int i = n - 1; i > 0; --i)
t[i] = t[2 * i] + t[2 * i + 1];
}
void update(int i, int val) { //更新线段树
i = i + n;
t[i] = val;
while (i > 0) {
t[i / 2] = t[i / 2 * 2] + t[i / 2 * 2 + 1];
i /= 2;
}
}
int sumRange(int i, int j) { //区域和检索
int l = i + n;
int r = j + n;
int sum = 0;
while (l <= r) {
if ((l % 2) == 1) {
sum += t[l];
l++;
}
if ((r % 2) == 0) {
sum += t[r];
r--;
}
l /= 2;
r /= 2;
}
return sum;
}
};