LeetCode 题解工作台
一维数组的动态和
给你一个数组 nums 。数组「动态和」的计算公式为: runningSum[i] = sum(nums[0]…nums[i]) 。 请返回 nums 的动态和。 示例 1: 输入: nums = [1,2,3,4] 输出: [1,3,6,10] 解释: 动态和计算过程为 [1, 1+…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 前缀和
答案摘要
我们直接遍历数组,对于当前元素 ,我们将其与前缀和 相加,即可得到当前元素的前缀和 。 时间复杂度 ,其中 为数组长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
给你一个数组 nums 。数组「动态和」的计算公式为:runningSum[i] = sum(nums[0]…nums[i]) 。
请返回 nums 的动态和。
示例 1:
输入:nums = [1,2,3,4] 输出:[1,3,6,10] 解释:动态和计算过程为 [1, 1+2, 1+2+3, 1+2+3+4] 。
示例 2:
输入:nums = [1,1,1,1,1] 输出:[1,2,3,4,5] 解释:动态和计算过程为 [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1] 。
示例 3:
输入:nums = [3,1,2,10,1] 输出:[3,4,6,16,17]
提示:
1 <= nums.length <= 1000-10^6 <= nums[i] <= 10^6
解题思路
方法一:前缀和
我们直接遍历数组,对于当前元素 ,我们将其与前缀和 相加,即可得到当前元素的前缀和 。
时间复杂度 ,其中 为数组长度。空间复杂度 。
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
return list(accumulate(nums))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ability to optimize space usage by modifying the array in-place.
- question_mark
Understanding of the prefix sum pattern and its efficiency in cumulative calculations.
- question_mark
Efficiency in both time and space while solving the problem, especially with the potential large input size.
常见陷阱
外企场景- error
Failing to update the array in-place or unnecessarily using extra space.
- error
Overcomplicating the solution by introducing unnecessary intermediate steps.
- error
Misunderstanding the prompt, leading to incorrect implementation of the cumulative sum.
进阶变体
外企场景- arrow_right_alt
Implement the solution using a recursive approach.
- arrow_right_alt
Handle cases where the array might contain negative numbers.
- arrow_right_alt
Return the prefix sum of a subarray rather than the entire array.