Topic:
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), 1sumRange (2, 5), -1sumrange (0, 5), 3
Note:
- Assume that the array does is not a change.
- There is many calls to sumrange function.
Your Numarray object would be instantiated and called as such:
Numarray Numarray (nums);
Numarray.sumrange (0, 1);
Numarray.sumrange (1, 2);
Ideas:
The solution of all sumrange (0, I) is obtained with bottom-up dynamic programming, and is stored in the public member solution ;
Sumrange (i, j) = Sumrange (0, J)-Sumrange (0, i-1);
Code: C + +
classNumarray { Public: Numarray (Vector<int> &nums) {num=Nums; if(Num.size () >0) {solution.push_back (num[0]); for(inti =1; I <= num.size ()-1; i++) { intindex = solution[i-1] +Num[i]; Solution.push_back (index); } } } intSumrange (intIintj) {if(I <0|| J >=num.size ())return 0; if(i = =0) returnSolution[j]; Else returnSOLUTION[J]-Solution[i-1]; } Vector<int>solution; Private: Vector<int>num; };
Leetcode 303. Range Sum query-immutable