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

Range Sum Query - Mutable

2017-04-05 20:15 302 查看
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.

Java代码:

public class NumArray {

       int[] bitset;
int[] nums;

void init(int i,int val){
   i++;
while(i<bitset.length){
bitset[i]+=val;
i+=(i&-i);
}
}

int getsum(int i){
int sum=0;
i++;
while(i>0){
sum+=bitset[i];
i-=(i&-i);
}
return sum;
}

public NumArray(int[] nums) {
        bitset=new int[nums.length+1];
        for(int i=0;i<nums.length;i++)init(i,nums[i]);
        this.nums=nums;
    }
    
    public void update(int i, int val) {
    int diff=val-nums[i];
    nums[i]=val;
        init(i,diff);
    }
    
    public int sumRange(int i, int j) {
        return getsum(j)-getsum(i-1);
    }
}

思路分析:使用树状数组,其中求index的低位用(index&-index)

时间复杂度:
update为O(Log(N)) 
init为O(N*Log(N))
sumRange为O(Log(N)) 
getSum为O(Log(N)) 
                 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: