到达一个数字的最少移动步数,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].

解决:

①  找到达到目标点最小步数,第n步移动的距离为n,往左或往右都可以。

这是一个偶函数,走到target和-target都是一样的,所以只考虑target>0的情况。

  • 如果能有n,使得sum = 1+2+...+n-1+n = target,显然,这是最佳方案。
  • 如果sum > target,需要前面有反方向走的。
    • 如果delta = (sum - target) 是偶数,设第i,j...步往反方向走,那么最后到达的距离是: sum - 2*(i+j+...),其中i, j...∈[1, n],由于delta是偶数,必定存在i,j,...,使得2*(i+j+...) = delta。所以这种情况下,最佳步数还是n。
    • delta = (sum - target) 是奇数,这样上面情况下的i, j...找不到,需要加步数。所以最后到达的距离是: sum - 2*(i+j+...) + n+1 + n+2 +...+ n+k ,现在需要找出最小的k。显然,k需要满足的条件是:使 sum + n+1 + n+2 +...+ n+k - delta 为偶数,即 n+1 + n+2 +...+ n+k 为奇数,这样就能找到符合条件的i,j,...。所以,当n是偶数时,n+1就是奇数,只需要加1步;否则,加2步。

例如:

  • 如果target = 3,那么n = 2,delta = 0,答案是n = 2。
  • 如果target = 4,那么n = 3,delta = 2,delta是偶数,答案是n = 3。
  • 如果target = 7,则n = 4,delta = 3,delta是奇数,并且加上n + 1使得delta是偶数。 答案是n + 1 = 5。
  • 如果target = 5,则n = 3,delta = 1,delta是奇数,并且加上n + 1保持delta奇数。 答案是n + 2 = 5。

class Solution { //9ms
    public int reachNumber(int target) {
        int n = 0;
        int sum = 0;
        target = Math.abs(target);
        while (sum < target){
            n ++;
            sum += n;
        }
        if ((sum - target) % 2 == 0){
            return n;
        }else {
            if (n % 2 == 0){
                return n + 1;
            }else {
                return n + 2;
            }
        }
    }

② 

class Solution { //9ms
    public int reachNumber(int target) {
        target = Math.abs(target);
        int k = 0;
        while(target > 0){
            target -= ++k;
        }
        return target % 2 == 0 ? k : k + 1 + k % 2;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1616706

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值