Range Sum Query - Immutable

题目详细信息如下:

Given an integer array nums, find the sum of the elements between indicesi 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
我的解法在下面,不过提交的时候给出了 超时的结论。大家如果有好的建议欢迎给我留言:

#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);    
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值