Reach a Number(到达目的地)

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

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

Return the minimum number of steps required to reach the destination.

Example 1:
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.
Example 2:
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 the range [-10^9, 10^9].

1.解析

题目大意,第n次移动n步,从X轴的起点出发,至少经过几次可以到达目的地。

2.分析

涉及求解至少经过几步,并且每次移动的状态都是可以枚举出来,一般都是考察BFS。最初我用的解法就是BFS,但BFS会TTL,原因在于求解的空间树是呈现指数级的增长,就是加上对应的剪枝也是无法解决的,虽然移动后所处的位置可能是一样的,但每次移动的步数是不确定的,故这些状态是无法去除的。

这道题主要涉及两个trick:

①目标位于X轴左右相同的位置,最终经过的次数是一样的,例如6和-6

0 + 1 = 1 ; 1 + 2 = 3 ; 3 + 3 = 6

位于-6,即将移动的位置取反。 

②当经过n步后,所走的距离为sum,超过target的差值为偶数,则可以认为经过n步即可到达目标位置,即相当于我们在(sum - target)/2的位置上取反即可;若差值为奇数,若当前n为偶数,则n+1为奇数,相当于再往前移动一次,即可到达目的地,若n为奇数,则需要继续走两次。

例如,目标位置为4

0 + 1 = 1 ; 1 + 2 = 3 ; 3 + 3 = 6

6 > 4, 但 6-4=2 的差值为偶数,相当于在 2 / 2 = 1这个位置上向反方向走,即

0 - 1 = -1 ; -1 + 2 = 1 ; 1 + 3 = 4

目标位置为5

0 + 1 = 1 ; 1 + 2 = 3 ; 3 + 3 = 6

6 > 5, 但 6-5=1 的差值为奇数,往前再走两次,即

0 + 1 = 1 ; 1 + 2 = 3 ; 3 + 3 = 6 ; 6 + 4 = 10 ; 10 - 5 = 5

class Solution {
public:
    int reachNumber(int target) {
        target = abs(target);
        int sum = 0, res = 0;
        while (sum < target || (sum-target) % 2 == 1) { //正好到达目的地或者超出目的地的距离为偶数
            ++res;
            sum += res;
        }

        return res;
    }
};

参考

[1]https://www.cnblogs.com/grandyang/p/8456022.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值