LeetCode 题解工作台
K 秒后第 N 个元素的值
给你两个整数 n 和 k 。 最初,你有一个长度为 n 的整数数组 a ,对所有 0 ,都有 a[i] = 1 。每过一秒,你会同时更新每个元素为其前面所有元素的和加上该元素本身。例如,一秒后, a[0] 保持不变, a[1] 变为 a[0] + a[1] , a[2] 变为 a[0] + a[1]…
5
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们注意到,整数 的范围是 $1 \leq n \leq 1000$,因此我们可以直接模拟这个过程。 我们定义一个长度为 的数组 ,并初始化所有元素为 。然后我们模拟 秒的过程,每一秒我们都更新数组 的元素,直到 秒结束。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你两个整数 n 和 k。
最初,你有一个长度为 n 的整数数组 a,对所有 0 <= i <= n - 1,都有 a[i] = 1 。每过一秒,你会同时更新每个元素为其前面所有元素的和加上该元素本身。例如,一秒后,a[0] 保持不变,a[1] 变为 a[0] + a[1],a[2] 变为 a[0] + a[1] + a[2],以此类推。
返回 k 秒后 a[n - 1] 的值。
由于答案可能非常大,返回其对 109 + 7 取余 后的结果。
示例 1:
输入:n = 4, k = 5
输出:56
解释:
| 时间(秒) | 数组状态 |
|---|---|
| 0 | [1,1,1,1] |
| 1 | [1,2,3,4] |
| 2 | [1,3,6,10] |
| 3 | [1,4,10,20] |
| 4 | [1,5,15,35] |
| 5 | [1,6,21,56] |
示例 2:
输入:n = 5, k = 3
输出:35
解释:
| 时间(秒) | 数组状态 |
|---|---|
| 0 | [1,1,1,1,1] |
| 1 | [1,2,3,4,5] |
| 2 | [1,3,6,10,15] |
| 3 | [1,4,10,20,35] |
提示:
1 <= n, k <= 1000
解题思路
方法一:模拟
我们注意到,整数 的范围是 ,因此我们可以直接模拟这个过程。
我们定义一个长度为 的数组 ,并初始化所有元素为 。然后我们模拟 秒的过程,每一秒我们都更新数组 的元素,直到 秒结束。
最后,我们返回 即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def valueAfterKSeconds(self, n: int, k: int) -> int:
a = [1] * n
mod = 10**9 + 7
for _ in range(k):
for i in range(1, n):
a[i] = (a[i] + a[i - 1]) % mod
return a[n - 1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate optimize a brute-force simulation approach using mathematical tricks like prefix sums?
- question_mark
Does the candidate understand the pattern of updating elements based on their predecessors?
- question_mark
Is the candidate comfortable with trade-offs between time and space complexity?
常见陷阱
外企场景- error
Overlooking the need for prefix sum optimization and resorting to a brute-force simulation, leading to inefficiency.
- error
Not correctly handling the simulation for large values of k, resulting in time limit exceeded errors.
- error
Misunderstanding the problem's structure and failing to implement the running sum technique effectively.
进阶变体
外企场景- arrow_right_alt
What if the array starts with different initial values instead of 1?
- arrow_right_alt
What if the problem only asks for the sum of the array instead of the last element after k seconds?
- arrow_right_alt
Can this approach be adapted for multidimensional arrays or more complex data structures?