0754. Reach a Number (M)

Reach a Number (M)

题目

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].


题意

在一根数轴上从0出发,第n步可以向左或向右走n步,问最少需要几步走到指定值。

思路

target正负不影响,为方便取target绝对值。先求出k,使得sum=1+2+...+k恰好大于target,如果sum-target为偶数,说明在1~k这k步中,只要第(sum-target)/2这一步变为向左走,就能正好到达target;如果sum-target为奇数,说明还需要再走1步或2步,使(sum+k+1-target)为偶数或(sum+k+1+k+2-target)为偶数,这样也能在1~k+1或1~k+2中选一步向左走,使得正好走到target。


代码实现

Java

class Solution {
    public int reachNumber(int target) {
        target = Math.abs(target);
        int step = 0, sum = 0;
        while (sum < target) {
            sum += ++step;
        }
        return (sum - target) % 2 == 0 ? step : step % 2 == 0 ? step + 1 : step + 2;
    }
}
posted @ 2020-12-29 13:57  墨云黑  阅读(60)  评论(0编辑  收藏  举报