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.
Detemine 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.
解题思路:直接利用贪心策略,遍历数组,对每个元素计算出当前位置的能够跳的最大长度,开始的时候,令maxStep = A[0],遍历数组时,maxStep--,比较maxStep和A[i],具体代码如下:
class Solution{
public:
bool CanJump(int A[], int n){
if (n == 0 || n == 1){
return true;
}
int maxStep = A[0];
for (int i = 1; i < n; i ++){
if (maxStep == 0){
return false;
}
maxStep --;
if (maxStep < A[i]){
maxStep = A[i];
}
if (maxStep + i >= n - 1){
return true;
}
}
}
};