您的位置:首页 > 其它

leetcode-45 Jump Game II

2015-10-20 22:09 579 查看
问题描述:

Given an array ofnon-negative integers, you are initially positioned at the first index of thearray.

Each element in the array represents your maximum jump length atthat position.

Your goal is to reach the last index in the minimum number ofjumps.

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算法;以[2,3,1,1,4]为例,对数组进行遍历,记下每一步能够到达的最远距离max;

    首先从第0步开始,其能到达的最远距离currMax为0+A[0]=2;则Step1能达到的最远位置为currMax;

继续遍历1-currMax范围内的数据,记录下来其中能够最远走到的位置,本例即为1+A[1]=4作为Step2的最远位置;

统计最终的step数即为所需要的结果。

同时也要注意如[1,0,0,0,0,4]这种无法到达最终终点的特殊情况。

 

代码:

public class Solution {
public int jump(int[] A) {
// step表示总步长,currMax表示当前能够走到的最远距离
int step = 0, currMax = 0;
// 进行一次遍历,nextMax用以记录在走到currMax过程中所能到达的最远距离
for (int i = 0, nextMax = 0; i < A.length - 1 && i <=currMax; i++) {
nextMax = Math.max(nextMax,i + A[i]);

// 记下每一步到达的最远点
if (i == currMax) {
currMax = nextMax;
step++;
}
}
// 要注意考虑无法达到终点的特殊情况
return currMax >= A.length - 1 ? step : -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: