题目
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.
Example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
思考
- 从前往后模拟整个过程:
把输入的数组遍历一遍,用一个数组把能到达的位置存起来,最后判断最后一个能否到达。
这个方法用时较长,因为每次都要把输入的数组遍历一遍,而且如果能走的步数大于1,还要额外的开销。 - 从后往前走,如果可以跳1步,就只跳1步,直到断了再检测是否可以跳更多的步数。
这个方法不一定需要把输入数组遍历一遍。
答案
c++
1.
class Solution {
public:
bool canJump(vector<int>& nums) {
bool reachable[1000000] = {false};
reachable[0] = true;
for (int i = 0; i < nums.size() - 1; i++) {
if (!reachable[i]) continue;
int temp = nums[i];
while(temp > 0) {
reachable[i + temp] = true;
temp--;
}
}
return reachable[nums.size() - 1];
}
};
2.
class Solution {
public:
bool canJump(vector<int>& nums) {
for (int i = nums.size() - 2; i >= 0; i--) {
if (nums[i] == 0) {
int temp = i - 1, offset = 1;
bool flag = false;
while (temp >= 0) {
if (nums[temp] > offset) {
i = temp;
flag = true;
break;
}
offset++;
temp--;
}
if (!flag) return false;
}
}
return true;
}
};