[11.4] 754. 到达终点数字

题目链接:754. 到达终点数字

解题思路

  1. 首先找到最接近的那个位置。由等差数列求和公式可以知道 s u m = ( x + 1 ) × x 2 sum = \frac{(x+1)\times x}{2} sum=2(x+1)×x。最接近的x是 ( 2 × s u m ) \sqrt{(2 \times sum)} (2×sum) .
  2. 如果正好当前的步数等于目标则返回。
  3. 如果不等,情况则为当前的步数超过了目标,此时可以分成两种情况:
    • 超过的步数是偶数。这种情况只需要将之前步数中的某一步换为往反方向跑即可。
      image.png

    • 超过的步数是奇数,那么继续往前走,直到超过的步数为偶数为止。

代码

class Solution:
    def reachNumber(self, target: int) -> int:
        if target < 0:
            target = -target
        # 等差数列找到最接近的一个k
        k = int((2 * target) ** 0.5)
        # 当前的位置
        cur = (1 + k) * k / 2
        while cur < target or (cur - target) % 2 == 1:
            k += 1
            cur = (1 + k) * k / 2
        return k

猜你喜欢

转载自blog.csdn.net/leeyns/article/details/127693838