I. Title Description
Given an integer array nums, find the sum of the elements between indices i and J (I≤J), inclusive.
Example:
Givennums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) ->1sumRange(2, 5) -> -1sumRange(0, 5) -> -3
Two. Topic analysis
Given an array, the sum of the subscripts nums i and the j elements between them is assumed to i be less than or equal, and the j array nums is generally invariant.
This problem should not look at the hint can think of a better than the method of violence, in the sumRange case, may be called multiple times, so if each call to the subscript interval elements to accumulate, will lead to inefficiency.
An improvement that can be taken is that, in the constructor NumArray(vector<int> &nums) , an array is entered nums , and all the elements from the first element to each subscript element are accumulated and saved to sums the corresponding position in the new array, so that each time the index is searched and the i j element is Just return directly: sums[j] - sum[i - 1] you can.
Three. Sample code
classNumarray { Public: Numarray ( vector<int>&nums) {if(Nums.empty ())return;Else{Sums.push_back (nums[0]);//For a given sequence length intLen = Nums.size (); for(inti =1; i < Len; ++i) Sums.push_back (Sums[i-1] + nums[i]); } }intSumrange (intIintj) {returnSUMS[J]-sums[i-1]; }Private://Storage sequence and vector<int>sums;};//Your Numarray object would be instantiated and called as such://Numarray Numarray (nums);//Numarray.sumrange (0, 1);//Numarray.sumrange (1, 2);
Leetcode notes: Range Sum query-immutable