forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add c/0303-range-sum-query-immutable.c
- Loading branch information
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
typedef struct { | ||
int size; | ||
int *sums; | ||
} NumArray; | ||
|
||
|
||
NumArray* numArrayCreate(int* nums, int numsSize) { | ||
NumArray *n = (NumArray*)malloc(sizeof(NumArray)); | ||
n->size = numsSize; | ||
n->sums = (int*)malloc(sizeof(int) * numsSize); | ||
|
||
// Pre calculate the sum of each index from 0. | ||
n->sums[0] = nums[0]; | ||
for(int i = 1; i < numsSize; i++){ | ||
n->sums[i] = n->sums[i-1] + nums[i]; | ||
} | ||
|
||
return n; | ||
} | ||
|
||
int numArraySumRange(NumArray* obj, int left, int right) { | ||
assert(obj); | ||
if (left == 0) { | ||
return obj->sums[right]; | ||
} | ||
return obj->sums[right] - obj->sums[left - 1]; | ||
} | ||
|
||
void numArrayFree(NumArray* obj) { | ||
if (obj) { | ||
free(obj->sums); | ||
free(obj); | ||
} | ||
} | ||
|
||
/** | ||
* Your NumArray struct will be instantiated and called as such: | ||
* NumArray* obj = numArrayCreate(nums, numsSize); | ||
* int param_1 = numArraySumRange(obj, left, right); | ||
* numArrayFree(obj); | ||
*/ |