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) -> 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.
C Solution:
typedef struct {
int *sums;
int sumsSize;
} NumArray;
NumArray* numArrayCreate(int* nums, int numsSize) {
NumArray *res = malloc(sizeof(NumArray));
res->sums = malloc((numsSize + 1) * sizeof(int));
res->sumsSize = numsSize + 1;
res->sums[0] = 0;
int i;
for (i = 0; i < numsSize; i++) {
res->sums[i + 1] = nums[i] + res->sums[i];
}
return res;
}
int numArraySumRange(NumArray* obj, int i, int j) {
return obj->sums[j + 1] - obj->sums[i];
}
void numArrayFree(NumArray* obj) {
free(obj->sums);
free(obj);
}
/**
* Your NumArray struct will be instantiated and called as such:
* struct NumArray* obj = numArrayCreate(nums, numsSize);
* int param_1 = numArraySumRange(obj, i, j);
* numArrayFree(obj);
*/
Summary:
- nothing to say.
LeetCode: 303. Range Sum Query - Immutable
近期评论