LeetCode 题解工作台

一维数组的动态和

给你一个数组 nums 。数组「动态和」的计算公式为: runningSum[i] = sum(nums[0]…nums[i]) 。 请返回 nums 的动态和。 示例 1: 输入: nums = [1,2,3,4] 输出: [1,3,6,10] 解释: 动态和计算过程为 [1, 1+…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 前缀和

bolt

答案摘要

我们直接遍历数组,对于当前元素 ,我们将其与前缀和 相加,即可得到当前元素的前缀和 。 时间复杂度 ,其中 为数组长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个数组 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
lightbulb

解题思路

方法一:前缀和

我们直接遍历数组,对于当前元素 nums[i]nums[i],我们将其与前缀和 nums[i1]nums[i-1] 相加,即可得到当前元素的前缀和 nums[i]nums[i]

时间复杂度 O(n)O(n),其中 nn 为数组长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        return list(accumulate(nums))
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

一维数组的动态和题解:前缀和 | LeetCode #1480 简单