题干:
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.
题目解析:
这道题是指给定一个数组,然后我们从第一个位置出发,每一个位置上的数据代表我们所能前进的最大步数,若能够到达最后一个位置,则返回true,若不能到达,则返回false。仔细分析这道题可以
知道,若到达的位置不是为0,则可以一直往前进,关键在于能不能越过0这个点。因此这里我们可以采用贪心的策略,每处于一个位置,则前进能前进的最大距离,即前进当前位置的数据的步数,若直接到达最后或者大于最后的位置,则都是返回true;若到达的位置数为0,意味着我们不能继续前进,此时往后退i格(能到达第k个位置,则前面k-i个位置都可以到达),若此格最大前进步数大于i,即可越过0,继续前进,若不能越过,则无法到达终点,返回false,因此算法实现如下:
class Solution {
public:
bool canJump(vector<int>& nums) {
int i = 0, num = nums.size();
if (nums[0] == 0 && num > 1) {
return false;
}
if (num == 1)
return true;
while (i < num) {
if (i == num - 1)
return true;
if (nums[i] != 0) {
i += nums[i];
} else {
int j = 1;
for (j = 1; j <= i; j ++) {
if (nums[i - j] > j) {
i -= j;
break;
}
}
if (j == i + 1 && nums[i] == 0)
return false;
}
}
return true;
}
};