题目

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:

  1. Input: target = 3
  2. Output: 2
  3. Explanation:
  4. On the first move we step from 0 to 1.
  5. On the second step we step from 1 to 3.

Example 2:

  1. Input: target = 2
  2. Output: 3
  3. Explanation:
  4. On the first move we step from 0 to 1.
  5. On the second move we step from 1 to -1.
  6. 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

  1. class Solution {
  2. public int reachNumber(int target) {
  3. target = Math.abs(target);
  4. int step = 0, sum = 0;
  5. while (sum < target) {
  6. sum += ++step;
  7. }
  8. return (sum - target) % 2 == 0 ? step : step % 2 == 0 ? step + 1 : step + 2;
  9. }
  10. }