Leetcode Note: Range Sum Query-Immutable
I. 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
Ii. Question Analysis
Given an arraynums, Returns the subscript.iAndjThe sum of elements.iMust be less than or equaljAnd ArraynumsGenerally, it remains unchanged.
This question should be able to think of a better solution than the brute-force method without looking at the prompts. In this question,sumRangeIt may be called multiple times. Therefore, if you accumulate the elements in the subscript interval during each call, the efficiency will be low.
The improvement method can be adopted in the constructorNumArray(vector &nums) Input an arraynumsThe sum of all elements from the first element to each subscript element is calculated and saved to the new array.sumsIn this way, the subscript is searched every timeiAndjBetween Elements, you only need to directly return:sums[j] - sum[i - 1]You can.
Iii. Sample Code
Class NumArray {public: NumArray (vector
& Nums) {if (nums. empty () return; else {sums. push_back (nums [0]); // obtain the length of a given series. int len = nums. size (); for (int I = 1; I <len; ++ I) sums. push_back (sums [I-1] + nums [I]);} int sumRange (int I, int j) {return sums [j]-sums [I-1];} private: // stores series and vector
Sums ;}; // Your NumArray object will be instantiated and called as such: // NumArray numArray (nums); // numArray. sumRange (0, 1); // numArray. sumRange (1, 2 );