Jump Game II

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

这道题目也是在条件判断上面出错了好久。

解题思路:

1.选出当前筛选范围里面能够达到最大跳的数组的位置。

findmax(int[] A, int i) 

即从A[i]开始,到A[i]+i结束筛选出能够达到最大跳的。

例如,以题目的A为例,findmax(A, 0) 

findmax={j|max{A[j]+j}&&i<=j<=A[i]+i}

但是,如果当前j已经达到了数组的末端,那么无需再选择max{A[j]+j}了。

例如A={5,8,1}如果findmax筛选出来j==1,但是实际上无需跳到1,因为j==0的时候已经可以跳到末端了。

所以在筛选出来的j中增加一条判断条件:

if(j>=A.length-1) j=A.length-1


2.从findmax中得到结果,count++,判断结果是否达到数组末端,

如果未达到数组末端,则findmax(A,findmax(A,j))


源代码如下:

public class Jump_Game_II {
	public int findmax(int[] A, int i) {
		int max = -1, index = 0;
		if (i >= A.length - 1)
			return i;
		for (int j = i + 1; j <= A[i] + i && j < A.length; ++j)
			//j <= A[i] + i && j < A.length导致的结果是不一样的,如果j==A.length-1就无需再选取前面中最大的了
		{	if (max < A[j] + j) {
				max = A[j] + j;
				index = j;
			}
			if(j>=A.length-1)return j;
		}
		System.out.println("--" + i + ":" + index + "," + max + "\n");
		return index;
	}

	public int jump(int[] A) {
		if (A.length == 1)
			return 0;
		int count = 0, eindex = 0;
		for (; eindex < A.length;) {
			count++;
			eindex = findmax(A, eindex);
			if(eindex>=A.length-1)return count;
			// eindex=A[eindex]+eindex;
		}
		return count;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] A = { 1,1,1,1,1};
		System.out.println("minimun jump=" + new Jump_Game_II().jump(A) + '\n');
	}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值