running sum of 1d array

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

Return the running sum of nums.

• Example 1:

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

• Example 2:

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

• Example 3:

Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]

Constraints:

1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6

# 思路

3 3
3 + 1 4
3+1+2 <=> 4+2 6
3+1+2+10 <=> 6+10 16
3+1+2+10+1 <=> 16+1 17
• 首先可是无论哪一个例子都有第一个值不变的情况，即get_nums[0] = nums[0]

• 后面的计算过程都可对应成
get_nums[m] = get_nums[m-1] + nums[m]

• 由于计算过程在得出get_nums[m]后，不会再次使用nums[m]，我们则可直接取消get_nums[]使用nums[m]来避免内存的开销！

# 解法

## java

``````class Solution {
public int[] runningSum(int[] nums) {
nums[0] = nums[0];

for(int m = 1; m < nums.length;m++){
nums[m] = nums[m] + nums[m-1];
}
return nums;
}
}
``````

## python3

``````class Solution:
def runningSum(self, nums: List[int]) -> List[int]: #这是新增的语法，为了说明参数和返回值的数据类型。不过仅仅的给人看的，实际上程序并不检查是否是相符的。
nums[0] = nums[0]
m = 1
while m < len(nums):
nums[m] = nums[m] + nums[m-1]
m += 1
return nums
``````
• sample 16ms submission

``````class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
var=[]
for i in range(len(nums)):
if i==0:
var.append(nums[i])
else:
var.append(var[i-1]+nums[i])
return var
``````

### 要不赞赏一下?

 微信 支付宝 PayPal Bitcoin

``https://www.emperinter.info/2020/09/09/running-sum-of-1d-array/``

## 优惠码

 阿里云国际版 20美元 Vultr 10美元 搬瓦工 | Bandwagon 应该有折扣吧？ Just My Socks JMS9272283 【注意手动复制去跳转】 域名 | namesilo `emperinter`(1美元) 币安 币安