Given an integer array in the construct method, implement two methods query(start, end)
and modify(index, value)
:
- For query(start, end), return the sum from index start to index end in the given array.
- For modify(index, value), modify the number in the given index to value
Notice
We suggest you finish problem Segment Tree Build, Segment Tree Queryand Segment Tree Modify first.
Example
Given array A = [1,2,7,8,5]
.
query(0, 2)
, return10
.modify(0, 4)
, change A[0] from 1 to 4.query(0, 1)
, return6
.modify(2, 1)
, change A[2] from 7 to 1.query(2, 4)
, return14
.
没用线段树, 竟然蒙过关了,也是醉了:
思路是这样的, 先把0-i的sum算出来存起来, 然后只存改变的index和dif,正真计算的时候在把dif加上:
class Solution {
public:
vector<long long> sum = {0};
vector<int> A;
vector<int> change;
unordered_map<int, int> dif_value;
/**
* @param A: An integer vector
*/
Solution(vector<int> A) {
// write your code here
this->A = A;
int t = sum[0];
for (int i = 0; i < A.size(); i++) {
t+=A[i];
sum.push_back(t);
}
}
/**
* @param start, end: Indices
* @return: The sum from start to end
*/
long long query(int start, int end) {
// write your code here
long long sum_dif_s = 0;
long long sum_dif_e = 0;
// for (int i = 0; i <change.size(); i++) {
// cout
// }
int prev_start = start - 1;
for (int i = 0; i < change.size(); i++) {
if (prev_start < change[i] && end <change[i]) {
break;
}
if (change[i] <= prev_start) {
sum_dif_s+=dif_value[change[i]];
}
if (change[i] <= end) {
sum_dif_e+=dif_value[change[i]];
}
}
// cout<<sum_dif_s<<endl;
// cout<<sum_dif_e<<endl;
long long real_sum = (sum[end + 1] + sum_dif_e) - (sum[start] + sum_dif_s);
return real_sum;
}
/**
* @param index, value: modify A[index] to value.
*/
void modify(int index, int value) {
// write your code here
//if (index < this->A.size())
int dif = value - A[index];
auto itr = lower_bound(change.begin(), change.end(), index);
if (itr == change.end() || *itr != index) {
change.insert(itr, index);
}
dif_value[index] = dif;
}
};