0754. Reach a Number (M)
阿新 • • 發佈:2020-12-29
Reach a Number (M)
題目
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
[-10^9, 10^9]
.
題意
在一根數軸上從0出發,第n步可以向左或向右走n步,問最少需要幾步走到指定值。
思路
target正負不影響,為方便取target絕對值。先求出k,使得sum=1+2+...+k恰好大於target,如果sum-target為偶數,說明在1~k這k步中,只要第(sum-target)/2這一步變為向左走,就能正好到達target;如果sum-target為奇數,說明還需要再走1步或2步,使(sum+k+1-target)為偶數或(sum+k+1+k+2-target)為偶數,這樣也能在1~k+1或1~k+2中選一步向左走,使得正好走到target。
程式碼實現
Java
class Solution {
public int reachNumber(int target) {
target = Math.abs(target);
int step = 0, sum = 0;
while (sum < target) {
sum += ++step;
}
return (sum - target) % 2 == 0 ? step : step % 2 == 0 ? step + 1 : step + 2;
}
}