This article is participating in the nuggets team number online activity, click to see the dachang spring recruiting positions

1. Title Description

The dynamic sum of a one-dimensional array

Second, train of thought analysis

Iterate over nums, getting the sum of the first I items each time and pushing the sum into the result array. The thing to notice is that the sum of the I terms before the first iteration is the value of the first.

AC code

Here I have four solutions, in order:

1. Add to your initial idea

var runningSum = function(nums) { let resArr = [], sum = 0; for(let i = 0; i < nums.length; i++){ sum = nums[i] + sum; resArr.push(sum); } return resArr; };Copy the code

2. Use the map

var runningSum = function(nums) {
    let sum = 0;
    return nums.map(item => sum += item);
};
Copy the code

3. Because the first item is a little special, so distinguish the first item and the following item, each time the result of the last traversal as the initial value of this traversal plus the turn of the value num[j], there is reduce() that taste, like a bad line, also not very traversal ~

var runningSum = function(nums) {
    let res = [];
    let sum = 0;
    for(let i = 0; i < nums.length; i++) {
        if(i >= 1) {
            for (let j = 0; j <= i; j++) {
                sum = res[i - 1] + nums[j];
            }
        } else {
            sum = nums[0];
        }
        res.push(sum);
    }
    return res;
};
Copy the code

4. Make use of reduce() ‘s built-in accumulation function

var runningSum = function(nums) {
    nums.reduce((prev, curr, index) => {
        nums[index] = prev + curr;
        return nums[index];
    }, 0);
    return nums;
};
Copy the code

Four,

The first thought of 1,1 is followed by the second thought of 2,3, and the second thought of reduce(), and the most ingenious 4. Welcome to add ~