Leetcode -- Jump Game II
来源:互联网 发布:奔驰换大灯编程教程 编辑:程序博客网 时间:2024/06/07 20:37
https://oj.leetcode.com/problems/jump-game-ii/
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.)
public int jump(int[] A)
问题分析:这题的解法就在于每次跳跃过程里,都选择下一步能够跳最远的那一格。第一步是没办法选的,必须是A[0],假设A[0]能够跳i步,那么在A[1]到A[i]之间,我们都维护下一步可能的最远距离,也就是A[k] + k ( 1 <= k <= i),然后到了第i格的时候,我们就跳最远的距离,然后步数加一。直到有一步能够跳到数组边界为止。难度不是很高,不知道为啥leetcode给了hard,给出代码如下:
public int jump(int[] A) { if(A.length <= 1) return 0; int step = 0; int next_max = A[0]; int cur_max = 0; for(int i = 0; i < A.length; i++){ if(cur_max >= A.length - 1) break; next_max = Math.max(A[i] + i, next_max); if(cur_max == i){ cur_max = next_max; step++; } } return step; }
0 0
- LeetCode: Jump Game II
- LeetCode Jump Game II
- LeetCode: Jump Game II
- [Leetcode] Jump Game II
- [LeetCode] Jump Game II
- [Leetcode] Jump Game ii
- leetcode Jump Game II
- leetcode Jump Game II
- [LeetCode]Jump Game II
- [leetcode]Jump Game II
- LeetCode-Jump Game II
- [leetcode] Jump Game II
- LeetCode - Jump Game II
- LeetCode:Jump Game II
- LeetCode | Jump Game II
- 【Leetcode】Jump Game II
- LeetCode Jump Game II
- [LeetCode] Jump Game II
- [暖手][学习阶段-各路杂题][HDU-1017]A Mathematical Curiosity
- Codeforces Round #288 (Div. 2) C. Anya and Ghosts
- 【SzNOI语法百题】【d014】判断直角三角形
- [C++]LeetCode: 129 Clone Graph (图的深拷贝 BFS && DFS)
- 【C/C++学院】(8)全局函数和类成员函数转化/友元/操作符重载
- Leetcode -- Jump Game II
- 微信公众号用户与网站用户的绑定方案
- Linux命令使用
- Apache+php+MySQL 安装注意细节及常见错误
- Cocos2d-x3.3Final(3) Button常用成员函数(C++)
- 顺序表的实现
- 网页调用ocx的方法
- 这两年比较看好的几个项目
- bootstrap+django快速构建一个blog