I'm working on a problem that requires the running sum within the array. Example, an array with the values [1,2,3,4] should return [1,3,6,10] and an array that holds [3,1,2,10,1] should output [3,4,6,16,17]. Right now I am stumped on what I am missing for my answer. I am thinking that I should handle this recursively in some way, but I am not sure how to begin with that. In any case, this is my current solution
var runningSum = function(nums) {
let result = [];
nums.forEach(function(num, idx) {
if (idx === 0) {
result.push(num);
} else {
result.push(num + nums[idx - 1]);
}
});
return result;
}
Leet code stated that this was a fairly easy problem, so I figured that I'm thinking way too hard on this and can solve it a lot easier. Let me know your thoughts. Thanks!
A simpler (and more resource-friendly) way of approaching the problem would just be to use a for
loop:
/**
* @param {number[]} nums
* @return {number[]}
*/
var runningSum = function(nums) {
for (let i = 1; i < nums.length; i++) nums[i] += nums[i-1];
return nums;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.