Q:
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.
题意大致是,给你提供一个二维数组,然后求指定下标之间的数之和,已知数组中的值可以更新,并且更新和求和操作会被频繁调用
Solution;
别看这道题和上几道题相似,解法其实完全不一样, (LeetCode 303) Range Sum Query - Immutable。
最原始的想法就是暴力遍历求和,不过想也不用想,当求和操作操作频繁调用,会超出给定时限。
并且,数组中的值会被频繁更新,我了解到的解决方法有Segement Tree(线段树),Binary Indexed Tree(树状数组) ,和平方根分解三种办法。树状数组真的是神作,很精巧的办法,也很高兴能够了解并学习这些数据结构。
我在这里提供线段树的解法,想了解树状数组的解法可以参考这篇博客:
(LeetCode 307) Range Sum Query - Mutable(树状数组讲解)
线段树,顾名思义,它的每一个结点代表一个区间。每个结点中包含的信息应该有该区间的起始下标
start
,结束下标
end
,左子树指针
left
,右子树指针
right
,以及我们需要计算的信息,如该区间的最大值
max
,最小值
min
,和
sum
等等。
我们这道题就使用到了
sum
这个信息,每个结点的左右子节点均分该结点区间,直到叶节点中的区间只含一个值。那么我们创建树的时间复杂度为
O(n)
,更新数的时间复杂度为
O(log(n))
,求和的时间复杂度也是
O(log(n))
class NumArray {
public:
struct SegmentNode
{
int start;
int end;
int sum;
SegmentNode *left;
SegmentNode *right;
SegmentNode(int start, int end){
this->start = start;
this->end = end;
this->sum = 0;
}
};
SegmentNode *root;
SegmentNode* buildTree(vector<int> &nums,int lo,int hi){
if(hi<lo)return nullptr;
SegmentNode *node = new SegmentNode(lo,hi);
if(hi==lo){
node->sum = nums[lo];
return node;
}
int mid = (lo+hi)/2;
node->left = buildTree(nums,lo,mid);
node->right = buildTree(nums,mid+1,hi);
node->sum = node->left->sum+node->right->sum;
return node;
}
void update(SegmentNode *node, int po,int val){
if(node->start==node->end&&node->start == po){
node->sum = val;
return;
}
if(po<node->start||po>node->end)
return;
int mid = (node->start+node->end)/2;
if(po<=mid){
update(node->left,po,val);
}
else{
update(node->right,po,val);
}
node->sum = node->left->sum + node->right->sum;
}
int sumRange(SegmentNode *node, int lo, int hi){
if(node->start==lo&&node->end ==hi)
return node->sum;
int mid = (node->start+node->end)/2;
if(hi<=mid) return sumRange(node->left,lo,hi);
else if(lo>mid) return sumRange(node->right,lo,hi);
else return sumRange(node->left,lo,mid)+sumRange(node->right,mid+1,hi);
}
NumArray(vector<int> &nums) {
this->root = buildTree(nums,0,nums.size()-1);
}
void update(int i, int val) {
update(root,i,val);
}
int sumRange(int i, int j) {
return sumRange(root,i,j);
}
};
不过时间消耗不那么乐观啊
Reference Link:
http://www.cnblogs.com/yrbbest/p/5056739.html