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:
- Assume that the array does is not a change.
- There is many calls to sumrange function.
Problem Solving Ideas:
The simplest dynamic programming. Complexity:numarray o (n) sumrange O (1)
To solve the boundary problem, establish ACCU = new int[nums.length+1] accu[i] to represent nums[0]+...+ Nums[i-1]
Recurrence Formula:accu[i] = Accu[i-1] + nums[i-1] Base case:accu[0]= 0
Java Code:
Public classNumarray {Private int[] accu; PublicNumarray (int[] nums) {Accu=New int[Nums.length+1]; accu[0] = 0; for(inti = 1; I<= nums.length; i++) {Accu[i]= Accu[i-1] + nums[i-1]; } } Public intSumrange (intIintj) {returnACCU[J+1]-Accu[i]; }}//Your Numarray object would be instantiated and called as such://Numarray Numarray = new Numarray (nums);//numarray.sumrange (0, 1);//Numarray.sumrange (1, 2);
Reference:
1. Https://leetcode.com/discuss/68725/5-lines-c-4-lines-python
2. Https://leetcode.com/discuss/69081/3ms-java-solution-with-array-no-special-i-0-check
Leetcode Range Sum query-immutable