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

LeetCode-Range Sum Query - Mutable

2016-03-28 11:01 483 查看
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.

public class NumArray {
private int[] tree;
private int[] num;

public NumArray(int[] nums) {
tree = new int[nums.length];
num = new int[nums.length];

Arrays.fill(tree,0);
Arrays.fill(num,0);
for (int i=0;i<nums.length;i++){
update(i,nums[i]);
}
}

void update(int i, int val) {
int delta = val-num[i];
num[i] = val;
int ind = i+1;

while (ind<=tree.length){
tree[ind-1] += delta;
ind += ind & (-ind);
}

}

private int sum(int i){
int ind = i+1;
int sum = 0;

while (ind>0){
sum += tree[ind-1];
ind -= ind & (-ind);
}
return sum;
}

public int sumRange(int i, int j) {
int a = sum(j);
int b = sum(i-1);
return a-b;
}

}

// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.update(1, 10);
// numArray.sumRange(1, 2);


Solution: it is an entry-level problem about Binary Indexed Tree.

Check BIT out: http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: