您的位置:首页 > 产品设计 > UI/UE

303. Range Sum Query - Immutable

2016-01-26 20:46 295 查看
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));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: