303. Range Sum Query - Immutable

303. Range Sum Query - Immutable
Difficulty: Easy

Given an integer array nums, find the sum of the elements between indices i 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
Note:
You may assume that the array does not change.
There are many calls to sumRange function.

给定一个整数序列,求指定子序列和。
提示:数组不会发生变化;大量sumRange函数调用。

题目本身非常简单,只需要遍历 i 到 j ,累计得到和即可。但是,这样是TLE(time limit exceeded)的,所给提示也就没有意义了。

所以,题目考察的是效能,换一个方向思考,我们可以存储前i个元素的和;
那么[i,j]子序列和 =sum[j]−sum[i−1];
注意,i==0时,直接返回sum[j]即可。

struct NumArray {
    int* a;
    int* sum;
    int len;
};

/** Initialize your data structure here. */
struct NumArray* NumArrayCreate(int* nums, int numsSize) {
    int i,temp;
    struct NumArray* numarray;
    numarray=(struct NumArray*)malloc(sizeof(struct NumArray));
    numarray->a=nums;
    numarray->len=numsSize;
    numarray->sum=(int*)malloc(numarray->len*sizeof(int));

    temp=0;
    for(i=0;i<numsSize;i++)    //记录前i个值之和
    {
        temp+=numarray->a[i];
        numarray->sum[i]=temp;
    }
    return numarray;
}

int sumRange(struct NumArray* numArray, int i, int j) {     

    if(i==0)     //若i=0直接为前j个值之和
        return numArray->sum[j];
    else         //若i>0则前j个值之和减去前i-1个值之和即为i到j的值之和
        return numArray->sum[j]-numArray->sum[i-1];

}

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

// Your NumArray object will be instantiated and called as such:
// struct NumArray* numArray = NumArrayCreate(nums, numsSize);
// sumRange(numArray, 0, 1);
// sumRange(numArray, 1, 2);
//  (numArray);

要点:
1,结构体指针需要初始化,

struct NumArray* numarray=(struct NumArray*)malloc  (sizeof(struct NumArray));

2,结构体指针的成员指针同样需要初始化,

numarray->sum=(int*)malloc(numarray->len*sizeof(int));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值