leetcode 303. Range Sum Query - Immutable
leetcode 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:
- You may assume that the array does not change.
- There are many calls to sumRange function.
由于题目说要提交很多次,所以考虑用动态规划,把从0开始的到i个元素的和放在数组里,以备之后使用。
1 public class NumArray { 2 private int[] dp; 3 4 5 public NumArray(int[] nums) { 6 dp=new int[nums.length+1]; 7 dp[0]=0; 8 for (int i=1;i<=nums.length;i++){ 9 dp[i]=dp[i-1]+nums[i-1]; 10 } 11 } 12 13 public int sumRange(int i, int j) { 14 return dp[j+1]-dp[i]; 15 } 16 } 17 18 /** 19 * Your NumArray object will be instantiated and called as such: 20 * NumArray obj = new NumArray(nums); 21 * int param_1 = obj.sumRange(i,j); 22 */