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

leetcode:Range Sum Query - Immutable

2015-12-08 09:02 357 查看
1、问题:

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.

求整数数组中某个范围的元素和。

2、My answer:

用C实现的,在跑case []时出错,提示runtime error。怀疑是在数组为空的时候返回值不符合case的要求,不确定应该返回什么,试过return 0, return -999, return。结果都一样。

Status:


Runtime Error

Submitted: 3 days, 18 hours ago
Last executed input:[]

source code:

struct NumArray {

int *pnums;

int num;

};

#define ERROR -999

/** Initialize your data structure here. */

struct NumArray* NumArrayCreate(int* nums, int numsSize) {

struct NumArray *pArray;

int i;

if ((numsSize <= 0) || (NULL == nums))

{

pArray = NULL;

return pArray;

}

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

pArray->pnums = (int *)malloc(numsSize);

if ((NULL == pArray) || (NULL == pArray->pnums))

return NULL;

pArray->pnums[0] = nums[0];

pArray->num = numsSize;

for (i=1; i<numsSize; i++)

{

pArray->pnums[i] = nums[i] + pArray->pnums[i-1];

}

return pArray;

}

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

int sum = 0;

if (NULL == numArray)

return;

if ((i >= numArray->num) || (j >= numArray->num) || (i < 0) || (j < 0))

return;

if (i > j)

{

i = i ^ j;

j = i ^ j;

i = i ^ j;

}

if (0 == i)

{

sum = numArray->pnums[j];

}

else

{

sum = numArray->pnums[j] - numArray->pnums[i-1];

}

return sum;

}

/** Deallocates memory previously allocated for the data structure. */

void NumArrayFree(struct NumArray* numArray) {

//free(numArray->pnums);

free(numArray);

free(numArray->pnums);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: