[leetcode] Jump Game
2014-07-21 11:50
399 查看
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 =
A =
思路:贪心,逐个遍历,每次计算当前位置能够前进的最大距离,当未到终点而能前进的最大距离为0时,返回false
代码:
class Solution {
public:
bool canJump(int A[], int n) {
if(n<=1) return true;
int maxstep=A[0];
if(A[0]==0) return false;
for(int i=1;i<n-1;i++){
maxstep=max(maxstep-1,A[i]);
if(maxstep==0) return false;
}
return true;
}
};
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.
思路:贪心,逐个遍历,每次计算当前位置能够前进的最大距离,当未到终点而能前进的最大距离为0时,返回false
代码:
class Solution {
public:
bool canJump(int A[], int n) {
if(n<=1) return true;
int maxstep=A[0];
if(A[0]==0) return false;
for(int i=1;i<n-1;i++){
maxstep=max(maxstep-1,A[i]);
if(maxstep==0) return false;
}
return true;
}
};
相关文章推荐
- 【LeetCode】55. Jump Game (Medium)
- LeetCode 55. Jump Game
- LeetCode 55: Jump Game
- leetcode 54: Jump Game
- Leetcode--Jump Game
- leetcode--Jump Game
- [leetcode]55. Jump Game(Java)
- 【Leetcode】之 Jump Game
- LeetCode 55 --- Jump Game
- Leetcode Jump Game
- LeetCode 55 Jump Game
- leetcode-jump game
- 【Leetcode】Jump Game
- LeetCode Jump Game
- [LeetCode]Jump Game
- LeetCode 55. Jump Game (跳跃游戏)
- 56 leetcode - Jump Game
- LeetCode——Jump Game
- leetcode: Jump Game--python
- [leetcode] 55. Jump Game 解题报告