LeetCode 题解工作台

到达终点数字

在一根无限长的数轴上,你站在 0 的位置。终点在 target 的位置。 你可以做一些数量的移动 numMoves : 每次你可以选择向左或向右移动。 第 i 次移动(从 i == 1 开始,到 i == numMoves ),在选择的方向上走 i 步。 给定整数 target ,返回 到达目标所需…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·搜索·答案·空间

bolt

答案摘要

由于对称性,每次可以选择向左或向右移动,因此,我们可以将 统一取绝对值。 定义 表示当前所处的位置,用变量 记录移动的次数。初始时 和 均为 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

在一根无限长的数轴上,你站在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 <= 109
  • target != 0
lightbulb

解题思路

方法一:数学分析

由于对称性,每次可以选择向左或向右移动,因此,我们可以将 target\textit{target} 统一取绝对值。

定义 ss 表示当前所处的位置,用变量 kk 记录移动的次数。初始时 sskk 均为 00

我们将 ss 一直循环累加,直到满足 stargets\ge \textit{target} 并且 (starget)mod2=0(s-\textit{target}) \bmod 2 = 0,此时的移动次数 kk 就是答案,直接返回。

为什么?因为如果 stargets\ge \textit{target}(starget)mod2=0(s-\textit{target})\mod 2 = 0,我们只需要把前面 starget2\frac{s-\textit{target}}{2} 这个正整数变为负数,就能使得 sstarget\textit{target} 相等。正整数变负数的过程,实际上是将移动的方向改变,但实际移动次数仍然不变。

时间复杂度 O(target)O(\sqrt{\left | \textit{target} \right | }),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
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
speed

复杂度分析

指标
时间O(\sqrt{\text{target}})
空间O(1)
psychology

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

到达终点数字题解:二分·搜索·答案·空间 | LeetCode #754 中等