LeetCode 题解工作台
找出 K 秒后拿着球的孩子
给你两个 正整数 n 和 k 。有 n 个编号从 0 到 n - 1 的孩子按顺序从左到右站成一队。 最初,编号为 0 的孩子拿着一个球,并且向右传球。每过一秒,拿着球的孩子就会将球传给他旁边的孩子。一旦球到达队列的 任一端 ,即编号为 0 的孩子或编号为 n - 1 的孩子处,传球方向就会 反转 …
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·结合·模拟
答案摘要
我们注意到,每一轮有 $n - 1$ 次传递,因此我们可以将 对 $n - 1$ 取模,得到 在当前轮的传递次数 ,然后我们将 除以 $n - 1$,得到当前的轮数 。 接下来我们判断当前的轮数 :
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·模拟 题型思路
题目描述
给你两个 正整数 n 和 k。有 n 个编号从 0 到 n - 1 的孩子按顺序从左到右站成一队。
最初,编号为 0 的孩子拿着一个球,并且向右传球。每过一秒,拿着球的孩子就会将球传给他旁边的孩子。一旦球到达队列的 任一端 ,即编号为 0 的孩子或编号为 n - 1 的孩子处,传球方向就会 反转 。
返回 k 秒后接到球的孩子的编号。
示例 1:
输入:n = 3, k = 5
输出:1
解释:
| 经过的时间 | 孩子队列 |
|---|---|
0 |
[0, 1, 2] |
1 |
[0, 1, 2] |
2 |
[0, 1, 2] |
3 |
[0, 1, 2] |
4 |
[0, 1, 2] |
5 |
[0, 1, 2] |
示例 2:
输入:n = 5, k = 6
输出:2
解释:
| 经过的时间 | 孩子队列 |
|---|---|
0 |
[0, 1, 2, 3, 4] |
1 |
[0, 1, 2, 3, 4] |
2 |
[0, 1, 2, 3, 4] |
3 |
[0, 1, 2, 3, 4] |
4 |
[0, 1, 2, 3, 4] |
5 |
[0, 1, 2, 3, 4] |
6 |
[0, 1, 2, 3, 4] |
示例 3:
输入:n = 4, k = 2
输出:2
解释:
| 经过的时间 | 孩子队列 |
|---|---|
0 |
[0, 1, 2, 3] |
1 |
[0, 1, 2, 3] |
2 |
[0, 1, 2, 3] |
提示:
2 <= n <= 501 <= k <= 50
注意:此问题与 2582. 递枕头 一致。
解题思路
方法一:数学
我们注意到,每一轮有 次传递,因此我们可以将 对 取模,得到 在当前轮的传递次数 ,然后我们将 除以 ,得到当前的轮数 。
接下来我们判断当前的轮数 :
- 如果 为奇数,那么当前的传递方向是从队尾到队首,因此会传递到编号为 的人手中;
- 如果 为偶数,那么当前的传递方向是从队首到队尾,因此会传递到编号为 的人手中。
时间复杂度 ,空间复杂度 。
class Solution:
def numberOfChild(self, n: int, k: int) -> int:
k, mod = divmod(k, n - 1)
return n - mod - 1 if k & 1 else mod
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate identify the repeating pattern in the ball's movement?
- question_mark
Does the candidate choose an optimized solution over brute force simulation?
- question_mark
Can the candidate handle the problem efficiently with larger k values?
常见陷阱
外企场景- error
Not recognizing the pattern in the ball's movement and resorting to unnecessary simulations.
- error
Failing to account for the direction reversal at the ends of the queue.
- error
Incorrectly handling small values of k, leading to off-by-one errors.
进阶变体
外企场景- arrow_right_alt
Consider larger values of n or k for performance testing.
- arrow_right_alt
Adjust the problem by having the ball start at a different position, or have different patterns of movement.
- arrow_right_alt
Implement the simulation with different boundary conditions, such as multiple reversals.