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.

这道题目与 Range Sum Query - Immutable这道题相比多了一个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);

猜你喜欢

转载自kickcode.iteye.com/blog/2272650
今日推荐