首页 > 代码库 > leetcode_Jump Game II

leetcode_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.Jump Game思路:和求Max Subarray类似,维护一个当前元素能够跳至的最大值,每循环一次更新reach=Math.max(nums[i]+1,reach),当i>reach或i>=nums.length的时候循环终止。最后看循环是否到达了最后,到达最后则返回true,否则,返回false.

2.和Jump Game不同的是,Jump Game II 让求的是跳过全部的元素至少须要几步。这须要维护一个局部变量edge为上一个reach,当i<=reach时,每次仍然通过Math.max(nums[i]+i,reach)获得最大的reach,当i>edge时,仅仅须要更新一个edge为当前reach就可以。并将minStep赋值为minStep+1。最后,当到达最后一个元素的时候说明能够到达最后,范围最少的步骤就可以。

代码:

public int jump(int[] nums)
	{
		int edge=0,reach=0;
		int minStep=0,i=0;
		for(;i<nums.length&&i<=reach;i++)
		{
			if(edge<i)
			{
				edge=reach;
				minStep=minStep+1;
			}
			reach=Math.max(nums[i]+i, reach);
		}
		if(i==nums.length)
			return minStep;
		return -1;
	}


leetcode_Jump Game II