您的位置:首页 > 产品设计 > UI/UE

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tree