303. Range Sum Query - Immutable 动态规划

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

 

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

 

因为在题目中说要call很多次sumRange,所以每次单独的循环去计算就比较累,可以在类的构造函数里面就把这个数组变成一个可以轻松表达区间和的形式,这样回头每次call就比较轻松了,用动态规划的思想,每一个的值依赖于当前的值减去上一个的值,每一段的和就等于俩边相减

 

class NumArray {
    int[] nums;
    public NumArray(int[] nums) {
        for(int i = 1; i < nums.length; i++){
            nums[i] = nums[i]+nums[i-1];
        }
        this.nums = nums;
    }
    
    public int sumRange(int i, int j) {
        if(i == 0) return nums[j];
        else return nums[j]-nums[i-1];
    }
}

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

 

posted @ 2019-04-30 13:38  星之眷属  阅读(108)  评论(0编辑  收藏  举报