题目
题目链接
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].
分析
- target的正负不影响计算结果,因为数轴是对称的
target = abs(target)
. - 找到整数n,使得$(\sum_{i=1}^n i) \geq target$.
- $有求和公式: target = \frac{n*(n+1)}{2}$.
- $整形得到一元二次方程: n^2+n-2*target=0$.
- $公式求解: n = \frac{(-1 + \sqrt{(1 + 8*target)})}{2}$.
- n可能不为整,向上取整即可.
- 取$sum = \frac{n*(n+1)}{2}$, sum 与 target 的差
diff = sum - target
- 此时,如果 sum == target,直接返回n即可. 又或者差值diff是偶数,那么只要把$\frac{\text{diff}}{2}$取反即可得到target,所以也是n.
- 若差值diff为奇数,则有如下两种情况:
- n为奇数,则n+1为偶数,需要$\sum_{i=1}^{n+2} i$ 来改变diff的奇偶.
- n为偶数,则n+1为奇数,$\sum_{i=1}^{n+1} i$ 来改变diff的奇偶.
代码
1 | class Solution { |