LeetCode 98 Jump Game
2014-10-27 20:23
351 查看
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
分析:
维护一个从当前能往后跳得最大步数step,随着遍历更新,如果step直到最后都大于0,那么说明可以,只要遇见step<=0的情况,即可停止。
public class Solution {
public boolean canJump(int[] A) {
if(A==null || A.length==0)
return false;
int step=A[0];//记录从当前开始能往后跳得步数
for(int i=1; i<A.length; i++){
if(step>0){
step--;//往前跳一步减1
step = math.Max(step, A[i]);
}else
return false;
}
return true;//直到最后step还大于0,说明可以跳到最后
}
}
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
分析:
维护一个从当前能往后跳得最大步数step,随着遍历更新,如果step直到最后都大于0,那么说明可以,只要遇见step<=0的情况,即可停止。
public class Solution {
public boolean canJump(int[] A) {
if(A==null || A.length==0)
return false;
int step=A[0];//记录从当前开始能往后跳得步数
for(int i=1; i<A.length; i++){
if(step>0){
step--;//往前跳一步减1
step = math.Max(step, A[i]);
}else
return false;
}
return true;//直到最后step还大于0,说明可以跳到最后
}
}
相关文章推荐
- LeetCode:Jump Game(Greedy DpUpdate)
- leetcode - Jump Game
- 【Leetcode】Jump Game
- LeetCode 55. Jump Game 解题报告
- Leetcode 55 Jump Game(第七周作业)
- LeetCode-Jump Game
- LeetCode: Jump Game
- LeetCode 55 Jump Game
- LeetCode 之 Jump Game(贪心算法)
- LeetCode 98: Validate Binary Search Tree
- [leetcode]55. Jump Game(Java)
- [Leetcode 55, Medium] Jump Game
- LeetCode (Jump Game)
- LeetCode(一) jump game
- Leetcode: Jump Game
- [LeetCode]Jump Game
- LeetCode题解:Jump Game
- [Leetcode] Jump Game
- [LeetCode 98] Validate Binary Search Tree
- LeetCode:Jump Game