1. 程式人生 > >leetcode_Jump Game II

leetcode_Jump Game II

sent nts represent 不同的 reac content [] 最後一個元素 當前

描寫敘述:

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