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

307. Range Sum Query - Mutable

2016-03-22 10:50 555 查看
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.

Subscribe to see which companies asked this question
树状数组,关于树状数组的详情可以参照http://baike.baidu.com/link?url=U7QI5Dr2xEufw9MuPWWTRQQuQCbdg9c5S6vXlDcweVUrT8z9RoQWC0qhjVQJUjPypWTOl4QGwe67QlQqz7u10q

public class NumArray {
int[] processed;
int[] nums;
int length;

public NumArray(int[] nums) {
length = nums.length;
processed = new int[length+1];
this.nums = nums;

//init processed
for(int i = 1;i<=length;i++){
int sum = 0;
int count = 1;
int counter = lowBit(i);

while(count <= counter){
sum += nums[i-count];
count++;
}
processed[i] = sum;
}
}

void update(int i, int val) {
//更新树状数组
int gap = val - nums[i];
nums[i] = val;

int index = i+1;
while(index <= length){
processed[index] += gap;
index += lowBit(index);
}
}

public int sumRange(int i, int j) {
return sum(j+1) - sum(i);
}

private int sum(int index){
int sum = 0;
while(index > 0){
sum += processed[index];
index -= lowBit(index);
}
return sum;
}
private int lowBit(int index){
return index & (-index);
}
}

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