[Leetcode] Range Sum Query - Immutable

这篇博客探讨了LeetCode中的一道题目,涉及如何在数组不变的情况下,求解给定索引范围i到j之间元素的和。举例说明了问题并指出题目对函数调用次数的考虑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

  1. You may assume that the array does not change.
  2. 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];
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值