← Static tasks

1480. Running Sum of 1d Array

leetcode easy

#array#csharp#easy#leetcode

Task

Дан массив nums. Мы определяем текущую сумму массива как runningSum[i] = сумма(nums[0]…nums[i]).

Верните массив текущих сумм для nums.

Пример:

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

C# solution

matched/original
public class Solution {
    public int[] RunningSum(int[] nums) {
        int[] result = new int[nums.Length];
        result[0] = nums[0];
        for (int i = 1; i < nums.Length; i++) {
            result[i] = result[i - 1] + nums[i];
        }
        return result;
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public vector<int>& RunningSum(vector<int>& nums) {
        vector<int>& result = new int[nums.size()];
        result[0] = nums[0];
        for (int i = 1; i < nums.size(); i++) {
            result[i] = result[i - 1] + nums[i];
        }
        return result;
    }
}

Java solution

matched/original
class Solution {
public int[] runningSum(int[] nums) {
        int[] result = new int[nums.length];

        result[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            result[i] = result[i - 1] + nums[i];
        }
        return result;
    }
}

JavaScript solution

matched/original
var runningSum = function(nums) {
    let result = Array(nums.length).fill(0);
    result[0] = nums[0];
    for (let i = 1; i < nums.length; i++) {
        result[i] = result[i - 1] + nums[i];
    }
    return result;
};

Python solution

matched/original
class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        result = [0] * len(nums)
        result[0] = nums[0]
        for i in range(1, len(nums)):
            result[i] = result[i - 1] + nums[i]
        return result

Go solution

matched/original
func runningSum(nums []int) []int {
    result := make([]int, len(nums))
    result[0] = nums[0]
    for i := 1; i < len(nums); i++ {
        result[i] = result[i-1] + nums[i]
    }
    return result
}

Explanation

Algorithm

1⃣Инициализация:

Определите массив result.

Инициализируйте первый элемент массива result первым элементом входного массива nums.

2⃣Вычисление текущих сумм:

На индексе i добавьте сумму элемента nums[i] и предыдущей текущей суммы result[i - 1] в массив result.

3⃣Повторение для всех индексов:

Повторите шаг 2 для всех индексов от 1 до n-1.

😎