-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path303-Range-Sum-Query-Immutable.c
49 lines (45 loc) · 1.06 KB
/
303-Range-Sum-Query-Immutable.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
typedef struct {
int numsSize;
int *nums;
int *sums;
} NumArray;
NumArray* numArrayCreate(int* nums, int numsSize) {
NumArray *newArray = (NumArray*)malloc(sizeof(NumArray));
newArray->numsSize = numsSize;
newArray->nums = nums;
newArray->sums = (int*)calloc(numsSize, sizeof(int));
for (int i = 0; i < numsSize; i++)
{
if (0 == i)
{
newArray->sums[i] = nums[i];
}
else
{
newArray->sums[i] = newArray->sums[i - 1] + nums[i];
}
}
return newArray;
}
int numArraySumRange(NumArray* obj, int i, int j) {
int sum = 0;
if (0 > i)
{
i = 0;
}
if (j > obj->numsSize - 1)
{
j = obj->numsSize - 1;
}
return obj->sums[j] - obj->sums[i] + obj->nums[i];
}
void numArrayFree(NumArray* obj) {
free(obj->nums);
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);
*/