Home algorithm - running sum of 1d array
Post
Cancel

algorithm - running sum of 1d array

Problem

https://leetcode.com/problems/running-sum-of-1d-array/?envType=study-plan&id=level-1

Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

Example

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].

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
    vector<int> runningSum(vector<int>& nums) {
        int len = nums.size();
        std:vector<int> ret;
        int tmp = 0;
        for (int i = 0; i< len; i++) {
            ret.push_back(tmp + nums[i]);
            tmp = ret[i];
        }
        return ret;
    }
};
This post is licensed under CC BY 4.0 by the author.