Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
The update(i, val) function modifies nums by updating the element at index i to val.
Example:
Given nums = [1, 3, 5]
sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
Note:
- The array is only modifiable by the update function.
- You may assume the number of calls to update and sumRange function is distributed evenly.
题意:
求数组区间和,并能够修改数组元素
思路:
直接模拟时间复杂度为
O(n2)
,必然不能通过。题目要求数组区间和并要修改元素值,这正好是树状数组的两个特性,可以用树状数组求解。时间复杂度为
O(nlog(n))
。具体思路见树状数组。
class NumArray {
public:
NumArray(vector<int> &nums) { //建立树状数组,注意树状数组的下标要从1开始。bit[0]中不保存元素。
num.resize(nums.size() + 1);
bit.resize(nums.size() + 1);
for (int i = 0; i < nums.size(); ++i) {
update(i, nums[i]);
}
}
void update(int i, int val) {//修改元素值的函数
int diff = val - num[i + 1];
for (int j = i + 1; j < num.size(); j += (j&-j)) {
bit[j] += diff;
}
num[i + 1] = val;
}
int sumRange(int i, int j) {//求区间和的函数
return getSum(j + 1) - getSum(i);
}
int getSum(int i) {//得到下标从0至i-1元素的区间和
int res = 0;
for (int j = i; j > 0; j -= (j&-j)) {
res += bit[j];
}
return res;
}
private:
vector<int> num;
vector<int> bit;
};
知识点:
树状数组