307. Range Sum Query

来源:互联网 发布:qq空间病毒式营销源码 编辑:程序博客网 时间:2024/06/02 03:05

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) -> 9update(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.

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 obj = new NumArray(nums); * obj.update(i,val); * int param_2 = obj.sumRange(i,j); */
原创粉丝点击