LeetCode 754. Reach a Number C++

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:

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].

Approach

1.这是一道找规律题,一开始打算用深搜或者广搜,可是当数字还没到达两位数时,就已经爆栈了,泪奔,题目大意很明显,就是从0走到target最少进行多少次,第i次要走i步。
2. 我们输出0~7次的时候可以走到哪

0
-1 1
-3 -1 1 3
-6 -4 -2 0 0 2 4 6
-10 -8 -6 -4 -4 -2 -2 0 0 2 2 4 4 6 8 10
-15 -13 -11 -9 -9 -7 -7 -5 -5 -5 -3 -3 -3 -1 -1 -1 1 1 1 3 3 3 5 5 5 7 7 9 9 11 13 15
-21 -19 -17 -15 -15 -13 -13 -11 -11 -11 -9 -9 -9 -9 -7 -7 -7 -7 -5 -5 -5 -5 -3 -3 -3 -3 -3 -1 -1 -1 -1 -1 1 1 1 1 1 3 3 3 3 3 5 5 5 5 7 7 7 7 9 9 9 9 11 11 11 13 13 15 15 17 19 21

3.从中可以看出两点,

  • 左右两边是这行的最小值和最大值

  • 行内的数字奇偶性一致

4.所以我们只要一直加到刚好大于target即可,但是因为存在奇偶,所以还要继续判断,直到该行的奇偶性与target一致

Code

class Solution {
public:
	int reachNumber(int target) {
		target = abs(target);
		int step = 0, sum = 0;
		while (sum < target || (sum - target) % 2 != 0) {
			sum += ++step;
		}
		return step;
	}
};

你可能感兴趣的:(Math)