Skip to content

Instantly share code, notes, and snippets.

@eckucukoglu
Last active February 8, 2016 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eckucukoglu/42c9aa805f78ef028521 to your computer and use it in GitHub Desktop.
Save eckucukoglu/42c9aa805f78ef028521 to your computer and use it in GitHub Desktop.
303. Range Sum Query - Immutable
#include <stdio.h>
#include <stdlib.h>
struct NumArray {
int *nums;
int numsSize;
};
/** Initialize your data structure here. */
struct NumArray* NumArrayCreate(int* nums, int numsSize) {
struct NumArray *numArray;
int i;
numArray = malloc (sizeof(struct NumArray) * 1);
numArray->nums = malloc (sizeof(int) * numsSize);
numArray->numsSize = numsSize;
numArray->nums[0] = nums[0];
for (i = 1; i < numsSize; i++) {
numArray->nums[i] = numArray->nums[i-1] + nums[i];
}
return numArray;
}
int sumRange(struct NumArray* numArray, int i, int j) {
int result = 0;
if (i == 0)
result = numArray->nums[j];
else
result = numArray->nums[j] - numArray->nums[i-1];
return result;
}
/** Deallocates memory previously allocated for the data structure. */
void NumArrayFree(struct NumArray* numArray) {
free(numArray->nums);
numArray->numsSize = 0;
numArray->nums = NULL;
}
int main() {
int numsSize = 1;
int *nums = malloc (sizeof(int) * numsSize);
nums[0] = -1;
struct NumArray* numArray = NumArrayCreate(nums, numsSize);
int result = sumRange(numArray, 0, 0);
NumArrayFree(numArray);
printf("%d\n", result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment