Range Sum Query - Mutable

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.

这道题目与[url=http://kickcode.iteye.com/blog/2272635]Range Sum Query - Immutable[/url]这道题相比多了一个update方法,这样我们就没法通过提前计算好sum来提高运算速度了。在这里我们介绍一种新的数据结构来解决这道题——树状数组(Binary Indexed tree)。这里简单介绍一下如何构造一个树状数组。
假设 给定一个数组nums[]。sumRange方法求其中连续多个数的和,update方法用来任意修改其中一个元素。下面我们构造树状数组BIT[]。其中的任意一个元素BIT[i]可能是一个或者多个nums数组中元素的和。我们如何确定BIT[i]包含的元素呢,这里我们用位运算的知识来处理。假设i的二进制表示中有k位连续的0,那么它就是数组nums中下面小于i的前2^k个元素的和。
注 *构造BIT数组时,BIT[0] = 0,代表空,
例如:
BIT[1] = nums[0] (1的二进制表示为0001,k = 0, 2 ^ k = 1, 因此只包含nums[0]).
BIT[2] = nums[0] + nums[1] (2 = 0010, k = 1, 2 ^ k = 2, 因此包含前两个元素).
BIT[3] = nums[2] (3 = 0011, k = 0, 2 ^ k = 1, 因此只包含一个紧邻3并且比3小的元素nums[2])
构建好BIT,这道题目就解决了,时间复杂度为O(logn), 代码如下:

public class NumArray {
int[] nums;
int[] BIT;

public NumArray(int[] nums) {
this.nums = nums;
BIT = new int[nums.length + 1];
for(int i = 0; i < nums.length; i++) {
init(i, nums[i]);
}
}
public void init(int i, int val) {
i ++;
while(i <= nums.length) {
BIT[i] += val;
i += (i & -i);
}
}
void update(int i, int val) {
int differ = val - nums[i];
nums[i] = val;
init(i, differ);
}
public int getSum(int i) {
i ++;
int sum = 0;
while(i > 0) {
sum += BIT[i];
i -= (i & -i);
}
return sum;
}
public int sumRange(int i, int j) {
return getSum(j) - getSum(i - 1);
}
}


// 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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值