754.Reach A Number
754.Reach A Number
难度:Easy
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.
1
Example 1:
2
Input: target = 3
3
Output: 2
4
Explanation:
5
On the first move we step from 0 to 1.
6
On the second step we step from 1 to 3.
7
Example 2:
8
Input: target = 2
9
Output: 3
10
Explanation:
11
On the first move we step from 0 to 1.
12
On the second move we step from 1 to -1.
13
On the third move we step from -1 to 2.
14
Note:
15
target will be a non-zero integer in the range [-10^9, 10^9].
Copied!
可以见得,最快的方式是直接等差数列递增过去。但是有时候会超过给定值,这时候就需要把一个数变为相反数。 变为相反数之后,总体值与原来相差两倍该变化值。因此如果递增和与给定值之差为偶数,则只需要改一个即可。如果为奇数,继续往后面走,知道为偶数即可。 正数与负数一样。 还需要注意整型溢出情况。
1
class Solution {
2
public:
3
int reachNumber(int target) {
4
if(target==0) return 0;
5
if(target<0) target= -target;
6
int len= (sqrt(1+8.0*target)-1)/2;
7
int sum=len*(len+1)/2;
8
if(sum == target) return len;
9
int res=sum +(++len)- target;
10
while(res%2)
11
res+=++len;
12
return len;
13
}
14
};
Copied!
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户 内存消耗 :8.2 MB, 在所有 C++ 提交中击败了81.69%的用户
Copy link