Leetcode notes: Range Sum query-immutable

Source: Internet
Author: User

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

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.