All numbers between any two numbers in the array, and

Source: Internet
Author: User

303. Range Sum query-immutable all numbers between any two numbers in the array, andQuestionEditorial SolutionMy Submissions
    • Total accepted:37248
    • Total submissions:146945
    • Difficulty:easy

Given an integer array nums, find the sum of the elements between indices I and J (iJ), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]sumrange (0, 2), 1sumRange (2, 5), -1sumrange (0, 5), 3

Note:

    1. Assume that the array does is not a change.
    2. There is many calls to sumrange function.

Subscribe to see which companies asked this question

1 //structure of the storage array2 structNumarray {3     intnum;4     intsum;5 };6 7 /** Initialize your data structure here.*/8 structnumarray* Numarraycreate (int* Nums,intnumssize) {9     inti =0;Ten     structNumarray *numarr = (structnumarray*)malloc(sizeof(structNumarray) *numssize);//array structure Body initialization One     structnumarray* p =Numarr; A     -     //non-empty array -     if(Numssize = =0) the         returnNULL; -          -     //Initialize first element -p[0].num = nums[0]; +p[0].sum = nums[0]; -i++; +      while(I <numssize) { AP[i].num =Nums[i]; atP[i].sum = p[i-1].sum +Nums[i]; -i++; -     } -      -     returnNumarr; - } in  - intSumrange (structnumarray* Numarray,intIintj) { to     //Sum[j]-sum[i] + num[i] +     return(Numarray[j].sum-numarray[i].sum +numarray[i].num); - } the  * /** Deallocates memory previously allocated for the data structure.*/ $ voidNumarrayfree (structnumarray*Numarray) {Panax Notoginseng      Free(Numarray); - } the  + //Your Numarray object would be instantiated and called as such: A //struct numarray* numarray = numarraycreate (Nums, numssize); the //Sumrange (numarray, 0, 1); + //Sumrange (Numarray, 1, 2); - //Numarrayfree (numarray);
View Code

All numbers between any two numbers in the array, and

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.