【前缀和】303.区域和检索-数组不可变

题目

法1:前缀和

class NumArray {
    private int[] preSumArray;

    public NumArray(int[] nums) {
        preSumArray = new int[nums.length + 1];
        for (int i = 1; i < nums.length + 1; ++i) {
            preSumArray[i] = preSumArray[i - 1] + nums[i - 1];
        }
    }
    
    public int sumRange(int left, int right) {
        return preSumArray[right + 1] - preSumArray[left];
    }
}

你可能感兴趣的:(前缀和)