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 =
The minimum number of jumps to reach the last index is
from index 0 to 1, then
问题分析:
问题求解最短距离,采取类似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;
}
}
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
1step
from index 0 to 1, then
3steps 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;
}
}
相关文章推荐
- 16道嵌入式C语言面试题(经典)
- 魅族 MX4,MX4 Pro,MX5等 android studio无法识别问题解决
- 日常总结(七)Java各种数据库连接
- C语言可变参数列表(1)
- SQL Server2005安装总结
- POJ 2429 GCD & LCM Inverse(Miller-Rabbin素性测试,Pollard rho质因子分解)
- C++中常用的三种参数传递方式
- 类似花生壳的代理本机服务至公网的ngrok以及pagekite
- 学习笔记06-多线程
- 【转】windows 签发 pfx 证书
- 深度优先算法
- 如何生成带注释的DLL文件
- iOS线程的简单学习<1>
- iOS初探+load和+initialize
- Linux下LVM配置过程
- 单维与多维线性回归代码( machine-learning-ex1 ) Stanford machine learning
- 音乐播放器项目技术之一音乐播放进度及音量的控制
- JAVA基础学习day25--Socket基础二-多线程
- CentOS 6.X学习心得
- 提升网站性能开发的10个技巧