Finding the dynamic sum of a one-dimensional array: LeetCode Question 1480

**Title:** Give you an array nums. The calculation formula of the array "prefix sum" is: rtSum[i] = sum(nums[0]…nums[i]).
Please return the prefix sum of nums
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: The prefix sum calculation process is [1, 1+2, 1+2 +3, 1+2+3+4].
Example 2:
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: The prefix and calculation process are [1, 1+1, 1+1+1 , 1+1+1+1, 1+1+1+1+1].
Example 3:
Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]

**Analysis:** Observing the law: the value of the i-th item is equal to the sum of the previous i-items (use loop accumulation)

//方法1:开辟一个新的数组 (时间复杂度O(n),空间复杂度O(n))
int* PreSum1(int* nums, int len)
{
    
    
	if (len == 0)
	{
    
    
		return NULL;//作个判断,如果数组长度为0,直接结束程序
	}

	int* brr = (int*)(malloc)(len * sizeof(int));//开辟一个新数组
	brr[0] = nums[0];//数组第一个元素就等于它本身
	for (int i = 1; i < len; i++)
	{
    
    
		brr[i] = brr[i - 1] + nums[i];
	}
	return brr;
}

**//改进**
//方法2:利用原数组保存结果 (时间复杂度O(n),空间复杂度O(1))
int* PreSum2(int* nums, int len)
{
    
    
	if(len == 0)
	{
    
    
		return NULL;
	}

	for (int i = 1; i < len; i++)
	{
    
    
		nums[i] += nums[i - 1];
	}
	return nums;
}

Guess you like

Origin blog.csdn.net/weixin_45824959/article/details/112981391