LWC 65: 754. Reach a Number
传送门:754. Reach a Number
Problem
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开始,第一步能够产生{ 1, -1}, 第二步能够产生{ 1, -1, 3, -3},我们枚举到第六步,有:
代码语言:javascript复制0
1
1 3
0 2 4 6
0 2 4 6 8 10
1 3 5 7 9 11 13 15
1 3 5 7 9 11 13 15 17 19 21
注意:每一个数字代表的是绝对值,也就是说正负都能取到。观察最后一列数字,有:
代码语言:javascript复制0
1
3
6
10
15
21
对应的有:
1 = 0 1
3 = 0 1 2 = 3
6 = 0 1 2 3 = 6
...
21 = 0 1 2 3 4 5 6 = 21
所以首先我们要确定step,最后一个数用sum来表示,如果target > sum说明还没加够,必须让sum >= target, 但发现每两行是同奇或同偶,所以如果sum - target为偶数,说明在此行,直接输出,如果为奇数,那么step必须还得往后数,此时,step为偶数时 1, step为奇数时 2.
Java版本:
代码语言:javascript复制 public int reachNumber(int target) {
target = Math.abs(target);
int sum = 0;
int n = 0;
while (sum < target){
n ;
sum = n;
}
if (sum == target) return n;
int res = sum - target;
if ((res & 1) == 0) {
return n;
}
else {
return n ((n & 1) == 0 ? 1 : 2);
}
}
Python版本:
代码语言:javascript复制class Solution(object):
def reachNumber(self, target):
"""
:type target: int
:rtype: int
"""
t = abs(target)
n = 0
sum = 0
while (t > sum):
n = 1
sum = n
if t == sum: return n
rem = sum - target
if (rem % 2) == 0: return n
else:
return n 1 if (n % 2) == 0 else n 2