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 steps to the last 3 index.)
Note:
You can assume so can always reach the last index.
Problem Solving Ideas:
Check where the nth jump is farthest, if the nth step of Maxreach >= n-1, then the answer is N. The first jump of the Maxreach is Numns[0] (the legend is equal to 5), the second jump of the Maxreach is head1 to MAX1 decision. The Maxreach of the third jump is determined by head2 and MAX2. And so on
1 classsolution (object):2 defJump (Self, nums):3 """4 : Type Nums:list[int]5 : Rtype:int6 """7n =Len (nums)8Njumps = Maxreach = head =09 Ten whileMaxreach < n-1: OneNjumps + = 1 ACurmax =Maxreach - forIinchRange (Head, maxreach+1): -Curmax = Max (Curmax, i+Nums[i]) theHead = Maxreach + 1 -Maxreach =Curmax - - returnNjumps
Leetcode 45. Jump Game II