Jump Game

来源:互联网 发布:阿里云 吉峰农机 编辑:程序博客网 时间:2024/06/05 00:52

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.)


方案:

使用广度遍历BFS的方法来解决,转化为树的 ,找到能到达叶子结点的最小层数


代码如下:

public class JumpGameII {public int jump(int[] nums){if(nums.length<2)return 0;int level=0;//记录当前层数,即走了几步int currentMax=0;//记录当前能走的最大步数int nextMax=0;//记录下一个可以走的最大步数int i=0;//每个数字都需遍历while(currentMax-i+1>0){//当前层的节点数level++;for(;i<=currentMax;i++){nextMax=Math.max(nextMax, nums[i]+i);if(nextMax>=nums.length-1)return level;}currentMax=nextMax;}return 0;}}




原创粉丝点击