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.
题目很清晰,求整型数组从i至j的元素值和,很容易想到循环求解,这里用链表方式实现了:
struct NumArray {
int val;
struct NumArray *next;
};
/** Initialize your data structure here. */
struct NumArray* NumArrayCreate(int* nums, int numsSize) {
struct NumArray *head = NULL, *tmpNext = NULL;
int i = 0;
if(!nums || numsSize <= 0)
return NULL;
while(numsSize --)
{
struct NumArray *tmp = malloc(sizeof(struct NumArray));
if(tmp == NULL){
return NULL;
}
tmp->val = nums[i++];
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tmpNext = head;
continue;
}
else
{
tmpNext->next = tmp;
tmpNext = tmp;
}
}
return head;
}
int sumRange(struct NumArray* numArray, int i, int j) {
if(NULL == numArray || i > j)
{
return 0;
}
int dist = j - i + 1;
int sum = 0;
struct NumArray *p = numArray;
while(i)
{
if(p->next){
p = p->next;
}
i --;
}
while(dist)
{
if(p){
sum += p->val;
p = p->next;
}
else{
break;
}
dist -= 1;
}
return sum;
}
/** Deallocates memory previously allocated for the data structure. */
void NumArrayFree(struct NumArray* numArray) {
struct NumArray*p = numArray;
while(p)
{
struct NumArray *tmp = p->next;
free(p);
p = tmp;
}
}
刚开始一直觉得这个题是不是太简单了,看了提示才知道这是要考查执行效率,试想这种求和要执行一万次,时间
会是多久?能否将时间尽量缩短?从答案给出的结果来看采用预先计算出从第一个元素到当前元素所有元素的和,保存下来,在函数sumRange中就可以很方便地不需要另外的循环计算该和了,这种使用“缓存(Cache)”的方式值得深思,尤其在日常工作中写代码要考虑好这一点是否可以沿用,给出答案以作日后参考。
private int[] sum;
public NumArray(int[] nums) {
sum = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
sum[i + 1] = sum[i] + nums[i];
}
}
public int sumRange(int i, int j) {
return sum[j + 1] - sum[i];
}