地址:http://oj.leetcode.com/problems/jump-game/
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
.
参考代码:
class Solution {
public:
bool canJump(int A[], int n) {
if(n)
{
int maxlen = A[0];
for(int i = 0; i < n && i<=maxlen; ++i)
{
if(i+A[i]>maxlen)
{
maxlen = i+A[i];
}
}
return maxlen>=n-1 ? true : false;
}
return true;
}
};
//SECOND TRAILclass Solution {public :bool canJump ( int A [], int n ) {if ( ! A || n < 0 )return false ;if ( n == 1 )return true ;int cur = 0 , end = A [ 0 ], maxstep = 0 ;while ( 1 ){while ( cur <= end ){maxstep = max ( maxstep , cur + A [ cur ]);++ cur ;if ( maxstep >= n - 1 )return true ;}if ( maxstep <= end )return false ;cur = end ;end = maxstep ;maxstep = 0 ;}return false ;}};
python:
class Solution :# @param A, a list of integers# @return a booleandef canJump ( self , A ):if not A :return Falseif len ( A ) == 1 :return True ;far = 0for i in range ( 0 , len ( A )):if i <= far :far = max ( far , i + A [ i ])if far >= len ( A ) - 1 :return Trueelse :return Falsereturn False