Leetcode Note: Range Sum Query-Immutable

Source: Internet
Author: User

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 );
   
  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.