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;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值