Give you an array of 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:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: The prefix and calculation process are [1, 1+2, 1+2+3, 1+2+3+4].
Solution 1: An additional array is defined to store the prefix sum of each item
int PreSum1(int *arr,int *Sum,int arr_length) //o(n) o(n)
{
if(arr_length <= 0)
return NULL;
for (int i = 0;i < arr_length;i++)
{
if (i == 0)
Sum[i] = arr[i];
else
Sum[i] = Sum[i - 1] + arr[i];
printf("%d ", Sum[i]);
}
}
The time complexity of this algorithm is O(n), and the space complexity is O(n), where the space complexity is too large.
Solution 2: Use the original array to save the prefix and
int PreSum2(int* nums, int numsSize, int* returnSize) //O(n),O(1)
{
for(int i=1;i<numsSize;i++)
{
nums[i] += nums[i-1];
}
*returnSize = numsSize;
return nums;
}
The time complexity of the algorithm is O(n), and the space complexity is O(1)