Comment on page
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.
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].
可以见得,最快的方式是直接等差数列递增过去。但是有时候会超过给定值,这时候就需要把一个数变为相反数。 变为相反数之后,总体值与原来相差两倍该变化值。因此如果递增和与给定值之差为偶数,则只需要改一个即可。如果为奇数,继续往后面走,知道为偶数即可。
正数与负数一样。 还需要注意整型溢出情况。
class Solution {
public:
int reachNumber(int target) {
if(target==0) return 0;
if(target<0) target= -target;
int len= (sqrt(1+8.0*target)-1)/2;
int sum=len*(len+1)/2;
if(sum == target) return len;
int res=sum +(++len)- target;
while(res%2)
res+=++len;
return len;
}
};
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户 内存消耗 :8.2 MB, 在所有 C++ 提交中击败了81.69%的用户