Jump Game II

1.题目描述(难度Hard)

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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.
Note:

You can assume that you can always reach the last index.

2.题目分析

题目要求:给你一个数组,数组中每位保存的是它可以向后走的最大步长,求最短可以走到数组末尾的步数。假设我们开始在初始的位置,即我们走0步就可以到达初始位置数组的index=0的地方。

解题思路:
这种题目,首先我想到的是树的广度优先遍历,从前往后遍历数组,每个index都可以有一个子树,如果遇到子树可以到达数组尾部,则范围当前的步数,后来发现,这个思路想复杂了。因为这种思路会有很多重复的计算,计算过的index向后会有很多重复。如果数组比较大的会,内存也会危险。
其实,依旧是广度优先遍历,只是每次我们有个范围,[begin, end],我们每走一步,就知道我们下一步的范围,我们只需要把当前范围内所能达到的最短最长处,作为下一个探索区间的范围即可。
每次向前走一个区间,我们都步数+1
当在某个区间能达到数组尾部时,我们返回当前的步数即可。

3.解题过程

Begin(算法开始)
输入 数组nums
计算数组的长度N,初始化起始位置begin和结束位置end都为0,当前走的步数steps=0
当结束位置end 当前步数steps+=1
maxIndex = end
for i in range(begin,end+1)
(因为range是[)所以,最后一个要比实际可以达到的+1)
gofar = i+nums[i]#当前位置可以达到最远的index
如果gofar>=N-1: return 当前steps
如果gofar>maxIndex:当前最大的maxIndex= gofar
上一轮循环完毕,我们重置begin,end = end+1,maxIndex
返回 steps//这个其实是留给上来就达到数组尾部的情况的
End (算法结束)

具体代码(python)已对应实现,但是测试用例代码还没完善,如上述思路有不足之处请批评指正。

你可能感兴趣的:(Jump Game II)