303. Range Sum Query - Immutable java solutions
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 private int[] sum; 3 public NumArray(int[] nums) { 4 sum = new int[nums.length+1]; 5 for(int i = 1; i < sum.length; i++) 6 sum[i] = sum[i-1] + nums[i-1]; 7 } 8 9 public int sumRange(int i, int j) { 10 return sum[j+1] - sum[i]; 11 } 12 } 13 14 15 // Your NumArray object will be instantiated and called as such: 16 // NumArray numArray = new NumArray(nums); 17 // numArray.sumRange(0, 1); 18 // numArray.sumRange(1, 2);
注意边界