Question

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

Solution

This problem can be transformed into "Given step n, what is the largest distance that you can reach?"

Beside maintaining an array to record farest reachable position, we need also know how farest current jump can reach.

Example

 public class Solution {
public int jump(int[] nums) {
if (nums == null || nums.length < 1)
return -1;
int length = nums.length;
// Three variables
// maxReach: max reachable position for current index and previous indexes
// maxJumpReach: max position that can be reachable by n jump steps
// jump: jump steps
int maxReach = nums[0];
int maxJumpReach = 0;
int jump = 0;
for (int i = 0; i < length && maxJumpReach <= (length - 1); i++) {
if (i > maxJumpReach) {
jump++;
maxJumpReach = maxReach;
}
maxReach = Math.max(maxReach, i + nums[i]);
}
return jump;
}
}

最新文章

  1. Mongodb启动命令mongod参数说明
  2. 原生JS封装简单动画效果
  3. Asp.net导出Excel乱码的解决方法
  4. 使用Android studio创建的AIDL编译时找不到自定义类的解决办法
  5. Link Management Protocol (LMP)
  6. css 样式设计(一)( 在线150个例子 | 背景 | 文本 | 字体 | 链接 | 列表 | 表格 | 盒模型 | 边框 | 轮廓 | 边距 | 填充 |分组和嵌套 | 尺寸 | 定位 | 浮动 |对齐 )
  7. CF 445A 简单DP
  8. iOS开发的22个奇谲巧技
  9. Peterson算法与Dekker算法解析
  10. Newton迭代法-C++
  11. Drawerlayou与ScrollView的介绍
  12. RabbitMQ系列教程之二:工作队列(Work Queues)
  13. 现代C++新四大名著及C++学习杂谈
  14. 201521123114 《Java程序设计》第2周学习总结
  15. oracle 列行转换
  16. 322. Coin Change零钱兑换
  17. 如何使用linux+xvfb+python+rfs+firefox+jenkins实现UI自动化
  18. 范进中Nature——儒林外史新义
  19. POJ-1038 Bugs Integrated, Inc. (状压+滚动数组+深搜 的动态规划)
  20. [Perforce]password (P4PASSWD) invalid or unset. 的错误解决

热门文章

  1. BufferedReader的ready与readLine使用,以及Premature EOF异常
  2. DELL WIN7系统安装 U盘
  3. 酷狗音乐QQ显示(VC源代码)
  4. python-生成随机字符
  5. overflow:hidden
  6. linq和lamda表达式中添加时间判断时解决方案
  7. C#中string.Empty和&quot;&quot;、null的区别
  8. DataList、Repeater、GridView中的Checkbox取值问题
  9. Nohttp请求图片的两种简答的方式:普通请求以及缓存请求
  10. iOS-OC-基础-NSString常用方法