Menu
CoddyTech

Running Sum of an Array

入门前缀和python iconjava iconcpp iconc iconjs icon+10

给定一个整数数组 nums。返回一个长度相同的新数组,其中索引 i 处的元素为 nums[0] + nums[1] + ... + nums[i],也就是前 i+1 个数的总和。

函数

runningSum(nums: integer-array) → integer-array
numsinteger-array
要从左到右相加的数字
返回值integer-array
nums 中每个元素对应的累计总和

约束条件

  • 1 ≤ nums.length ≤ 5000
  • -104 ≤ nums[i] ≤ 104
  • 每个累计值都能用 32 位有符号整数表示。

示例

输入
nums = [3, 1, 4, 1, 5]
输出
[3, 4, 8, 9, 14]
解释
继续相加:3,然后计算 3 + 1 = 4、4 + 4 = 8、8 + 1 = 9 和 9 + 5 = 14。每个总和都放到最后一个被加数对应的索引处。
challenge icon

进阶

你能为网格构建同样的结构吗?网格中的每个单元格都保存从左上角到该单元格所构成矩形的总和。

重置代码
def runningSum(nums):
    # 在这里编写代码

测试 #1

测试 #2

测试 #3

参数

nums = [3, 1, 4, 1, 5]

预期输出

[3, 4, 8, 9, 14]