JAVA算法:移动到终点的数字(Reach a Number)
在一根无限长的数轴上,你站在0的位置。终点在target的位置。
每次你可以选择向左或向右移动。第 n 次移动(从 1 开始),可以走 n 步。
返回到达终点需要的最小移动次数。
示例 1:
输入: target = 3
输出: 2
解释:
第一次移动,从 0 到 1 。
第二次移动,从 1 到 3 。
示例 2:
输入: target = 2
输出: 3
解释:
第一次移动,从 0 到 1 。
第二次移动,从 1 到 -1 。
第三次移动,从 -1 到 2 。
注意:
target是在[-10^9, 10^9]范围中的非零整数。
算法设计
package com.bean.algorithm.basic;public class ReachANumber {// calculate sum(1->x)public static int f(int x) {return (x * (x + 1) / 2);}public static int reachNumber(int target) {target = Math.abs(target);if (target == 0)return 0;// find the min num x that has f(x)>=target. This is O(1) due to while loop runs// in several stepsint vmin = (int) Math.sqrt(target);while (f(vmin) < target)++vmin;// find the proper step. This is also O(1) due to while_loop take small steps.while (f(vmin) % 2 != target % 2)vmin++;return vmin;}public static void main(String[] args) {// TODO Auto-generated method stubint target = 3;int result = reachNumber(target);System.out.println("RESULT = " + result);}}
程序运行结果:
RESULT = 2