0%

leetcode1480 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
2
3
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].

分析

    今天是一道Easy的题,这题用的算是一个挺常用的算法,很多涉及到累加的题目都会用到。思路是,第i个累加的结果为nums[i]加上第i-1个累加的结果,即 res[i] = res[i-1] + nums[i]。

python 代码

1
2
3
4
5
6
7
8
9
10
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
if not nums:
return []

res = [nums[0]]
for i in range(1, len(nums)):
res.append(res[-1]+nums[i])

return res