LeetCode 题解工作台
到达终点数字
在一根无限长的数轴上,你站在 0 的位置。终点在 target 的位置。 你可以做一些数量的移动 numMoves : 每次你可以选择向左或向右移动。 第 i 次移动(从 i == 1 开始,到 i == numMoves ),在选择的方向上走 i 步。 给定整数 target ,返回 到达目标所需…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
由于对称性,每次可以选择向左或向右移动,因此,我们可以将 统一取绝对值。 定义 表示当前所处的位置,用变量 记录移动的次数。初始时 和 均为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
在一根无限长的数轴上,你站在0的位置。终点在target的位置。
你可以做一些数量的移动 numMoves :
- 每次你可以选择向左或向右移动。
- 第
i次移动(从i == 1开始,到i == numMoves),在选择的方向上走i步。
给定整数 target ,返回 到达目标所需的 最小 移动次数(即最小 numMoves ) 。
示例 1:
输入: target = 2 输出: 3 解释: 第一次移动,从 0 到 1 。 第二次移动,从 1 到 -1 。 第三次移动,从 -1 到 2 。
示例 2:
输入: target = 3 输出: 2 解释: 第一次移动,从 0 到 1 。 第二次移动,从 1 到 3 。
提示:
-109 <= target <= 109target != 0
解题思路
方法一:数学分析
由于对称性,每次可以选择向左或向右移动,因此,我们可以将 统一取绝对值。
定义 表示当前所处的位置,用变量 记录移动的次数。初始时 和 均为 。
我们将 一直循环累加,直到满足 并且 ,此时的移动次数 就是答案,直接返回。
为什么?因为如果 且 ,我们只需要把前面 这个正整数变为负数,就能使得 与 相等。正整数变负数的过程,实际上是将移动的方向改变,但实际移动次数仍然不变。
时间复杂度 ,空间复杂度 。
class Solution:
def reachNumber(self, target: int) -> int:
target = abs(target)
s = k = 0
while 1:
if s >= target and (s - target) % 2 == 0:
return k
k += 1
s += k
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(\sqrt{\text{target}}) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Ask why the cumulative sum minus target parity matters for valid sequences.
- question_mark
Probe if the candidate considers both positive and negative targets efficiently.
- question_mark
Check if they identify the quadratic growth of sums and optimize using binary search instead of linear iteration.
常见陷阱
外企场景- error
Ignoring the parity condition can lead to incorrect minimal move counts.
- error
Attempting a linear search over moves without exploiting cumulative sum patterns wastes time.
- error
Failing to normalize the target can cause redundant calculations for negative positions.
进阶变体
外企场景- arrow_right_alt
Find the minimal moves to reach multiple targets simultaneously using the same incremental move pattern.
- arrow_right_alt
Compute the number of distinct sequences of moves that reach the target with minimal steps.
- arrow_right_alt
Extend to restricted moves where certain step sizes are forbidden, requiring adjustments in the binary search.