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:
You may assume that the array does not change.
There are many calls to sumRange function.
class NumArray { private final int[] arr; public NumArray(int[] nums) { this.arr = new int[nums.length]; int sum = 0; for(int i = 0; i < nums.length; i++){ sum += nums[i]; arr[i] = sum; } } public int sumRange(int i, int j) { return arr[j] - (i == 0 ? 0 : arr[i - 1]); } }
arr[i]是nums数组从0到i(包括)的sum,所以要求i,j之间的和,先判断i是否为0,然后等于arr[j] - arr[i - 1]。
以上是dp解法。