您的位置:首页 > 其它

[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 = 
[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 算法