Algorithm series-leetcode-1480. Dynamic sum of one-dimensional arrays

1480. Dynamic Sum of 1D Arrays (Simple)

gives you an array  nums . The calculation formula of the array "dynamic sum" is: runningSum[i] = sum(nums[0]…nums[i]) .

Please return  nums the dynamic and.

Example 1:

Input: nums = [1,2,3,4]
 Output: [1,3,6,10]
 Explanation: The dynamic and 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 dynamic and calculation process is [1, 1+1, 1+1+1, 1+ 1+1+1, 1+1+1+1+1] .

prefix and

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var runningSum = function(nums) {
    for(let i = 1; i < nums.length; i++){
        nums[i] += nums[i - 1]
    }
    return nums
};

reduce

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var runningSum = function(nums) {
    nums.reduce((prev, curr, index) => {
        nums[index] = prev + curr
        return nums[index]
    }, 0)
    return nums
};

Guess you like

Origin blog.csdn.net/animatecat/article/details/124549580