leetcode-303 区域和检索 - 数组不可变 [Java]

类别:

题目:

leetcode-303 区域和检索 - 数组不可变 [Java]_第1张图片

leetcode-303 区域和检索 - 数组不可变 [Java]_第2张图片

法一:直接计算

代码:

class NumArray {
    int[] nums;
    
    public NumArray(int[] nums) {
        this.nums=nums;
    }

    public int sumRange(int left, int right) {
        int sum = 0;
        for (int i = left; i <= right; i++) {
            sum += nums[i];
        }
        return sum;
    }
}

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(left,right);
 */

结果:

leetcode-303 区域和检索 - 数组不可变 [Java]_第3张图片 

法二:优化一下

        每次计算sumRange都要从i遍历到j相加,不如先计算前缀和,再相减。

代码:

class NumArray {
    int[] sums;
    
    public NumArray(int[] nums) {
        //计算前缀和
        int n=nums.length;
        sums=new int[n+1];
        sums[0]=nums[0];
        for (int i = 0; i < n; i++) {
            sums[i+1]=sums[i]+nums[i];
        }
    }

    public int sumRange(int left, int right) {
        //做减法
        return sums[right+1]-sums[left];
    }
}

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(left,right);
 */

结果:

leetcode-303 区域和检索 - 数组不可变 [Java]_第4张图片

 

 

 

你可能感兴趣的:(leetcode-Code,java,leetcode,算法)