LeetCode307 Range Sum Query-Mutable

Given an integer array nums, find the sum of the elements between indices i and j (ij), 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:

1. The array is only modifiable by the update function.

2. You may assume the number of calls to update and sumRange function is distributed evenly.


这个问题相比其简单版本,多了一个更新数组的功能,因此用原来的方法求解时,会出现超时的问题。

点开show tags标签后,看到了Binary Indexed Tree,就去学习一下。

Binary Indexed Tree,也叫树状数组,主要是阅读了下面这个博客。了解后发现,这个数据结构用来解决这个问题刚刚好!

http://blog.csdn.net/int64ago/article/details/7429868


class NumArray {
public:
    NumArray(vector<int> &nums) {
		v.push_back(0);
		for(int i = 0; i < nums.size(); i++)
			v.push_back(nums[i]);
		tree.push_back(0);
        for(int i = 1; i < v.size(); i++){
        	tree.push_back(v[i]);
        	int k = (i&-i)-1, j = 1;
			while(k--){
				tree[i] += v[i-j];
				j++;
			}
		}
    }
    void update(int i, int val) {
    	int x = val-v[i+1];
    	v[i+1] = val;
        tree[i+1] += x;
        i++;
        i += (i&-i);
        while(i < tree.size()){
        	tree[i] += x;
        	i += (i&-i);
		}
    }
    int getSum(int i){
    	int sum = 0;
    	i++;
    	while(i>0){
    		sum += tree[i];
    		i -= (i&-i);
		}
		return sum;
	}
    int sumRange(int i, int j) {
    	if(i == 0) return getSum(j);
        return getSum(j)-getSum(i-1);
    }
    
    vector<int> tree;
    vector<int> v;
};


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

// 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);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值