Skip to content

Commit 86fa354

Browse files
committed
dp
1 parent cf789cf commit 86fa354

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

303-Range-Sum-Query-Immutable.c

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
typedef struct {
2+
int numsSize;
3+
int *nums;
4+
int *sums;
5+
} NumArray;
6+
7+
NumArray* numArrayCreate(int* nums, int numsSize) {
8+
NumArray *newArray = (NumArray*)malloc(sizeof(NumArray));
9+
newArray->numsSize = numsSize;
10+
newArray->nums = nums;
11+
newArray->sums = (int*)calloc(numsSize, sizeof(int));
12+
for (int i = 0; i < numsSize; i++)
13+
{
14+
if (0 == i)
15+
{
16+
newArray->sums[i] = nums[i];
17+
}
18+
else
19+
{
20+
newArray->sums[i] = newArray->sums[i - 1] + nums[i];
21+
}
22+
}
23+
return newArray;
24+
}
25+
26+
int numArraySumRange(NumArray* obj, int i, int j) {
27+
int sum = 0;
28+
if (0 > i)
29+
{
30+
i = 0;
31+
}
32+
if (j > obj->numsSize - 1)
33+
{
34+
j = obj->numsSize - 1;
35+
}
36+
return obj->sums[j] - obj->sums[i] + obj->nums[i];
37+
}
38+
39+
void numArrayFree(NumArray* obj) {
40+
free(obj->nums);
41+
free(obj);
42+
}
43+
44+
/**
45+
* Your NumArray struct will be instantiated and called as such:
46+
* struct NumArray* obj = numArrayCreate(nums, numsSize);
47+
* int param_1 = numArraySumRange(obj, i, j);
48+
* numArrayFree(obj);
49+
*/

0 commit comments

Comments
 (0)