LeetCode | 754. Reach a Number 数学原理题解析与证明

Youare standing at position 0 on an infinite number line. There is a goal at position target.

Oneach move, you can either go left or right. During the n-thmove (starting from 1), you take n steps.

Returnthe minimum number of steps required to reach the destination.

Example1:

Input: target = 3

Output: 2

Explanation:

On the first move we step from 0 to 1.

On the second step we step from 1 to 3.

Example2:

Input: target = 2

Output: 3

Explanation:

On the first move we step from 0 to 1.

On the second move we step from 1 to -1.

On the third move we step from -1 to 2.

Note:

· target will be a non-zero integer in therange [-10^9, 10^9].

给你一个数,第n次可以向左走,也可以向右走,问你最少多少次可以走到目的地

一开始我考虑的是广度优先遍历解决,但是这样的话由于target太大,内存超了,于是只好考虑其他的方法,思考过后我发现这题用数学的方法解决其实很简单,首先,要到达目的地一定会有向左和向右,我们假设一定有一个最好的方案,a1,a2,a3…an,假如a1到an都是正数,那么它一定是最好的方案,假如存在负数,那么可以看成把a1,a2…an里面的若干个数变成负数,然后到达target,可以证明,当a1+a2..an-target为偶数的时候,只需要把a1,a2,…an里面的一个数变成负数就能到达目的地,这就是最好的方案

当a1+a2..an-target为奇数的时候,有两种情况,当n为偶数的时候,n+1为奇数,可以证明,当把a1,a2..an里面一个数变成负数之后,只要在加一个数就能到达target,也就是a1+a2…an+an+1一定可以到达target,当n为奇数的时候,可以证明当把a1,a2..an里面一个数变成负数之后只要在加两个个数就能到达target,也就是a1+a2…an+an+1+an+2,所以有以下算法

class Solution {

public:

intreachNumber(int target) {

      int feiBo = 0, i; target = abs(target);

      for (i = 1; feiBo < target; feiBo += i,i += 1); i--;

     

      if (abs(feiBo - target) % 2 == 0) returni;

      else

      {

            if (i % 2 == 0) return i + 1;

            else

            return i + 2;

      }

}

};

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值