754. Reach a Number

754. Reach a Number

题目描述

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
2
3
4
5
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:

1
2
3
4
5
6
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].

题目大意

向右或者向左移动 N 次, 每一次移动 N 步,求至少需要移动多少步才能终点。

解题思路

按照数学思想,先找规律。
2: 1 - 2 + 3 sum = 3, N = 2 + 1,
3: 1 + 2 sum = 3, N = 3,
4: 1 + 2 - 3 + 4 sum = 6, N = 3 + 1,
5: 1 - 2 - 3 + 4 + 5 sum = 6, N = 3 + 2,
6: 1 + 2 + 3 sum = 6, N = 3,
7: 1 + 2 + 3 - 4 + 5 sum = 10, N = 4 + 1,
8: -1 + 2 + 3 + 4 sum = 10, N = 4,
9: 1 + 2 - 3 + 4 + 5 sum = 10, N = 4 + 1,
10: 1 + 2 + 3 + 4 sum = 10, N = 5,
可得规律:if (sum - target) % 2 == 0 返回 n 即可
if n % 2 == 1 return n + 1
else return n + 2

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
func reachNumber(_ target: Int) -> Int {
var sum = 0
var n = 0
let target = abs(target)
while sum < target {
sum += n
n += 1
}
if (sum - target) % 2 == 0 {
return n - 1
}else {
if n % 2 == 1 { return n }
else { return n + 1 }
}
}
}
0%