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 (i ≤ J), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]sumrange (0, 2), 1sumRange (2, 5), -1sumrange (0, 5), 3
Note:
- Assume that the array does is not a change.
- 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