Differential array tool class

Differential array tool class

What is a difference array

In fact, the difference array is somewhat similar to the prefix and array.
The prefix sum is mainly applicable to the case where the original array will not be modified, and the cumulative sum of a certain interval needs to be frequently queried.

preSum[ i ] is the cumulative sum of all elements of nums[ 0…i-1
] If you want the cumulative sum of nums[ i…j ], then calculate preSum[ j+1 ]-preSum[ i ]

Differential arrays are mainly suitable for frequent addition and subtraction of elements in a certain range of the original array (that is, the original array needs to be changed frequently)

diff[0]=nums[0]
diff[i] is nums[ i ]-nums[ i-1 ] adding 3
to the elements of nums[ i...j ], just let diff[i]+=3 first, then Just let diff[j+1]-=3
diff[i]+=3 is equivalent to adding 3 to the elements of nums[i...]
diff[j+1]-=3 is equivalent to nums[j+1 The elements of ] are all reduced by 3.
The combination of these two steps is to add 3 to the elements of nums[ i...j ]

Tools

// 差分数组工具类
class Difference {
    
    
    // 差分数组
    private int[] diff;
    
    /* 输入一个初始数组,区间操作将在这个数组上进行 */
    public Difference(int[] nums) {
    
    
        assert nums.length > 0;
        diff = new int[nums.length];
        // 根据初始数组构造差分数组
        diff[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
    
    
            diff[i] = nums[i] - nums[i - 1];
        }
    }

    /* 给闭区间 [i, j] 增加 val(可以是负数)*/
    public void increment(int i, int j, int val) {
    
    
        diff[i] += val;
        if (j + 1 < diff.length) {
    
    
            diff[j + 1] -= val;
        }
    }

    /* 返回结果数组 */
    public int[] result() {
    
    
        int[] res = new int[diff.length];
        // 根据差分数组构造结果数组
        res[0] = diff[0];
        for (int i = 1; i < diff.length; i++) {
    
    
            res[i] = res[i - 1] + diff[i];
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/weixin_52055811/article/details/131974100
Recommended