JAVA算法:移动到终点的数字(Reach a Number)

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 steps
		int 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 stub

		int target = 3;
		int result = reachNumber(target);
		System.out.println("RESULT = " + result);
	}

}

程序运行结果:

RESULT = 2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值