题目详细信息如下:
Given an integer array nums, find the sum of the elements between indicesi and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3我的解法在下面,不过提交的时候给出了 超时的结论。大家如果有好的建议欢迎给我留言:
#include<stdio.h>
struct NumArray {
int num;
struct NumArray * next;
};
/** Initialize your data structure here. */
struct NumArray* NumArrayCreate(int* nums, int numsSize) {
struct NumArray *numArray, *tmp;
numArray = (struct NumArray*) malloc(sizeof(struct NumArray));
numArray->num = *nums;
numsSize--;
nums++;
tmp = numArray;
while(numsSize > 0){
tmp->next = (struct NumArray*) malloc(sizeof(struct NumArray));
tmp->next->num = *nums;
tmp = tmp->next;
nums++;
numsSize--;
}
return numArray;
}
int sumRange(struct NumArray* numArray, int i, int j) {
int sum, tmpi;
struct NumArray *tmp;
tmp = numArray;
sum = tmpi = 0;
while(tmpi < i && tmp != NULL){
tmp = tmp->next;
tmpi++;
}
if(tmp == NULL) exit(-1);
while(tmpi <= j && tmp != NULL){
sum += tmp->num;
tmp = tmp->next;
tmpi++;
}
return sum;
}
/** Deallocates memory previously allocated for the data structure. */
void NumArrayFree(struct NumArray* numArray) {
struct NumArray *tmp;
tmp = numArray;
while(tmp != NULL){
numArray = numArray->next;
free(tmp);
tmp = numArray;
}
}
int main(void){
int nums[] = {-2, 0, 3, -5, 2, -1};
struct NumArray *numArray;
numArray = NumArrayCreate(nums, 6);
printf("%d\n", sumRange(numArray, 0, 2));
NumArrayFree(numArray);
return 0;
}
下面是我修改为数组后的版本,依然有运行超时的问题:
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);
for(i = 0; i < numsSize; i++)
numArray[i].num = nums[i];
return numArray;
}
int sumRange(struct NumArray* numArray, int i, int j) {
int sum;
sum = 0;
for(; i <= j; i++)
sum += numArray[i].num;
return sum;
}
/** Deallocates memory previously allocated for the data structure. */
void NumArrayFree(struct NumArray* numArray) {
free(numArray);
}