LeetCode 303. Range Sum Query – Immutable

Problem:

Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

Solution:

new to C, took a while.

struct NumArray {
    int* myNums;
    int* sums;
};

/** Initialize your data structure here. */
struct NumArray* NumArrayCreate(int* nums, int numsSize) {
    struct NumArray* numArray = malloc(sizeof(struct NumArray));
    numArray->myNums = nums;
    numArray->sums = malloc(numsSize * sizeof(int));
    for (int i = 0; i < numsSize; i++) {
        numArray->sums[i] = 0;
        for (int j = 0; j <= i; j++) {
            numArray->sums[i] += numArray->myNums[j];
        }
    }
    return numArray;
}

int sumRange(struct NumArray* numArray, int i, int j) {
    return numArray->sums[j] - numArray->sums[i] + numArray->myNums[i];
}

/** Deallocates memory previously allocated for the data structure. */
void NumArrayFree(struct NumArray* numArray) {
    free(numArray);
}