在discuss里看到一位存在的算法,他的算法里的思想为我打开了另一扇门,传送门聪明人的解法.
下面是我实现的C语言版本。呵呵,大家见笑啦!看来提交不能通过的问题,自己还没有深入思考,改之!
#include<stdio.h>
struct NumArray {
int num;
};
/** Initialize your data structure here. */
struct NumArray* NumArrayCreate(int* nums, int numsSize) {
struct NumArray *numArray;
int i;
numArray = (struct NumArray*) malloc(sizeof(struct NumArray) * numsSize);
numArray[0].num = nums[0];
for(i = 1; i < numsSize; i++)
numArray[i].num = nums[i] + numArray[i-1].num;
return numArray;
}
int sumRange(struct NumArray* numArray, int i, int j) {
if(i == 0) return numArray[j].num;
return numArray[j].num - numArray[i-1].num;
}
/** Deallocates memory previously allocated for the data structure. */
void NumArrayFree(struct NumArray* numArray) {
free(numArray);
}
主调函数大家可以去上一篇里去找。