0%

LeetCode 1480. Running Sum of 1d Array

題目

1
2
3
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

解法思維

foreach()依序相加,再回傳

1
2
3
4
5
6
7
8
9
var runningSum = function(nums) {
let total=[]
let sum=0
nums.forEach(item => {
sum+=item
total.push(sum)
});
return total
};

reduce()依序相加,再回傳

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* @param {number[]} nums
* @return {number[]}
*/
var runningSum = function(nums) {
/*
The current array index is increamented by the accumlator which is the new value of arr[i]

Example trace:

input:
[1,2,3,4]

acc i arr return value
0 0 1,2,3,4 0 + 1 = 1
1 1 1,2,3,4 1 + 2 = 3
3 2 1,3,3,4 3 + 3 = 6
end => 6 3 1,3,6,4 6 + 4 = 10
10 4 1,3,6,10

*/
nums.reduce((acc, _, i, arr) => arr[i] += acc )
return nums

};