Range Sum Query - Mutable
2016-04-21 14:31
417 查看
Problem
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
自己创建一个segment tree的数据结构老是超时。。参考了官方的答案,用数组来实现一个数,挺巧妙的。
class NumArray {
int N;
vector<int> tree;
int find( int left, int right) {
if(left > right) return 0;
if(left == right) return tree[left];
int sum = 0;
if( left%2 == 1 ){
sum += tree[left++];
}
if(right%2 == 0 ) {
sum += tree[right--];
}
return sum += find( left/2, right/2);
}
public:
NumArray(vector<int> &nums): N(nums.size()) {
tree.resize(2*N,0);
for( int i = N; i < 2*N; i++){
tree[i] = nums[i-N];
}
for( int i = N - 1; i > 0; i--){
tree[i] = tree[2*i] + tree[2*i+1];
}
}
void update(int idx, int val) {
idx += N;
int diff = val - tree[idx];
while(idx != 0) {
tree[idx] += diff;
idx /= 2;
}
}
int sumRange(int i, int j) {
return find( i + N, j + N);
}
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.update(1, 10);
// numArray.sumRange(1, 2);
相关文章推荐
- 命令行快速技巧:如何定位一个文件
- jquery+CSS实现的多级竖向展开树形TRee菜单效果
- cmd tree命令 以树形格式罗列文件
- 实例讲解jQuery EasyUI tree中state属性慎用
- 推荐8款jQuery轻量级树形Tree插件
- tree 以树形格式罗列文件
- EasyUI Tree+Asp.net实现权限树或目录树导航的简单实例
- E3 tree 1.6在Firefox下显示问题的修复方法
- js树形控件脚本代码
- swing中Tree与滚动条用法实例分析
- Spark Decision Tree
- 实例讲解jQuery EasyUI tree中state属性慎用
- 带check的treeView
- extjs 4 treepanel locked and expand
- JQuery EasyUI 实现tree的右键菜单
- flex tree 的两个小技巧
- Tree.log
- gnome文件管理器(nautilus)树形结构文件窗口 多窗口
- 排序binary tree
- python递归实现Easyui combotree树