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.
First try to see if we can get answer by just summing up values. If we undercount just add the next step.
If we overcount then we have to look at the difference between the sum and target.
The reason why we can't have odd values as the difference is because if we swap a value from negative to
positive we don't just lose the value. We lose double the value. Right?
If our sum is:
1 + 2 + 3 + 4 + 5 = 15
Say we flip 3 -> -3. We don't just have sum = 12 now. We have sum = 9.
1 + 2 -3 + 4 + 5 = 9 = 15 - 2(3).
So whenever you subtract any value from the sum you really lose double the value. And we know all even
numbers are double some other number. Therefore our difference between our target and sum has to be even.
classSolution{publicintreachNumber(int target){
target = Math.abs(target);int step =0;int sum =0;while(sum < target){
step++;
sum += step;}while((sum - target)%2!=0){
step++;
sum += step;}return step;}}
welcome to my blogLeetCode 754. Reach a Number (Java版; Medium)题目描述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 lef...