Range|Range Sum Query - Immutable

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]
【Range|Range Sum Query - Immutable】sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
Careful of timeout.
struct NumArray { int size; int *sum; };
/** Initialize your data structure here. */
struct NumArray* NumArrayCreate(int* nums, int numsSize) { struct NumArray* numArray; numArray=(struct NumArray*)calloc(1,sizeof(struct NumArray)); numArray->sum=(int*)calloc(numsSize+1, sizeof(int)); numArray->size=numsSize; numArray->sum[0]=0; for(int i=0; isum[i+1]=numArray->sum[i]+nums[i]; return numArray; } int sumRange(struct NumArray* numArray, int i, int j) { int sum=0; if(!numArray) return 0; sum=numArray->sum[j+1]-numArray->sum[i]; return sum; } /** Deallocates memory previously allocated for the data structure. */ void NumArrayFree(struct NumArray* numArray) { free(numArray->sum); free(numArray); } // Your NumArray object will be instantiated and called as such: // struct NumArray* numArray = NumArrayCreate(nums, numsSize); // sumRange(numArray, 0, 1); // sumRange(numArray, 1, 2); // NumArrayFree(numArray);

    推荐阅读