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
.
理解题意:
当前的A[i]值代表,当前能跳的最大值,并不是一定要跳这么远的,比如A[0]=3,那么我们可以跳0到3步。
这道题的关键:搞清楚结束条件。
注意这道题, LeetCode的测试有bug,那就是可以设定结束条件为:A[i] == 0 return false. 那样可以使用贪心法在LeetCode上AC。
但是明显这个是错误的,比如:{2,3,0,2,0,2};这个应该是真。
所以判定这里的判断结束条件应该是:
记录lastJump的位置,循环i到lastJump,所有位置,找出其中的最大值maxJump =max{ i+A[i]};如果这个区间内的最大值maxJump <= lastJump,那么就返回假,因为没有任何一个位置可以跳出这个位置。
如果没有这样的位置,一直可以跳到最后,那么就返回为真。
class Solution
{
public:
bool canJump(int A[], int n) {
int maxJump = 0;
int lastJump = 0;
int i = 0;
while (maxJump < n-1)
{
if (i+A[i] > maxJump) maxJump = i+A[i];
if (i >= lastJump)
{
if (maxJump <= lastJump) return false;
lastJump = maxJump;
}
i++;
}
return true;
}
};
2014-1-29 update
bool canJump(int A[], int n)
{
int last = 0;
int max_step = 0;
for (int i = 0; i < n-1; i++)
{
max_step = max(max_step, A[i]+i);
if (i == last)
{
if (max_step == i) return false;
last = max_step; //max_step = 0; 可以不重置,后面的数一定大于前面的
}
}
return true;
}