Describe:
Given an array of non-negative integers, you is initially positioned at the first index of the array.
Each element of the array represents your maximum jump length is 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 and then 3 steps to the last index.)
Ideas:
1.Jump game ideas: like Max Subarray, maintain a maximum value that the current element can jump to, update Reach=math.max (Nums[i]+1,reach) once per loop, when I>reach or i>= The loop terminates at the end of the nums.length, and finally the loop arrives at the end and returns true at the end, otherwise, false.
2. Unlike the jump game, jumping game II lets you skip all elements at least a few steps, which requires maintaining a local variable edge for the last reach when I<=reach, each time still passing through Math.max (Nums[i]+i, REACH) to obtain the maximum reach, when I>edge, only need to update an edge for the current reach, and assign Minstep to minstep+1. Finally, when the last element is reached, it is possible to reach the last, least-scoped step.
Code:
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;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode_jump Game II