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].
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reach-a-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1. target和-target的结果是一样的,所以我们只要求出target的绝对值的结果就好了。
2. 按照步数累加,假设target是8,我们先把步数累加到刚好大于等8
第一步:0 + 1 = 1
第二步:1 + 2 = 3
第三步:3 + 3 = 6
第四步:6 + 4 = 10
目标是8,现在算出来是10,那么相差2,这样子的话,那就要把第一步,变成减号,那么就造了一个2的落差了:
第一步:0 - 1 = -1
第二步:-1 + 2 = 1
第三步:1 + 3 = 4
第四步:4 + 4 = 8
这么看,就是说,先把数字累加到大约等于target,然后计算出差值diff,如果diff是偶数,那么直接把第diff/2步取反就好了。也就是说,8和10的步数是一样的。
现在我们看奇数的场景:如果现在target是9,是奇数,那么就只能往下走一步:
第五步:10 + 5 = 15
看15和9的差值是偶数,那么9和15的步数就是一样的,即target = 9,那么ans = 5.所以,如果当前找到的刚好超过的target的数字num,步数是n,但是差值是奇数,而且下一个要加的数字是奇数,那么只要往下走一步就能满足了,即答案是n + 1.
那么如果往下走一步还是奇数呢?现在target是14:
第一步:0 + 1 = 1
第二步:1 + 2 = 3
第三步:3 + 3 = 6
第四步:6 + 4 = 10
第五步:10 + 5 = 15
差值是1,往下走一步:
第六步:15 + 6 = 21
差值是7,再往下走一步:
第七步:21 + 7 = 28
差值是14,是偶数,那么target是14的就等于target是28的步数,即答案是7.也就是说,如果当前找到的刚好超过的target的数字num,步数是n,但是差值是奇数,而且下一个要加的数字是偶数,那么就还得再加一步,那么结果就是n+2。
所以,我们算出来,要走n步走到num,num大于等target,计算出差值diff = num - target
diff为偶数,直接返回n;
diff为奇数:
1. 下一步n + 1为奇数,那么返回n + 1
2. 下一步n + 1为偶数,返回n + 2
class Solution {
public int reachNumber(int target) {
target = Math.abs(target);
int res = 0, sum = 0;
while (sum < target) {
++res;
sum += res;
}
int diff = sum - target;
if (diff % 2 == 0) {
return res;
} else {
if (res % 2 == 0) {
return res + 1;
} else {
return res + 2;
}
}
}
}