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.
本题比较简单,代码如下:
1 public class NumArray { 2 int[] sum; 3 public NumArray(int[] nums) { 4 sum = new int[nums.length+1]; 5 for(int i=0;i<nums.length;i++){ 6 sum[i+1] = sum[i]+nums[i]; 7 } 8 } 9 10 public int sumRange(int i, int j) { 11 return sum[j+1]-sum[i]; 12 } 13 } 14 15 /** 16 * Your NumArray object will be instantiated and called as such: 17 * NumArray obj = new NumArray(nums); 18 * int param_1 = obj.sumRange(i,j); 19 */