Description
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 1
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.
Solution 1(C++)
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size()==1) return true;
int len=nums.size()-1;
for(int i=len-1; i>=0; i--){
for(int j=i; j>=0 && nums[j]>=len-j; j--){
if(j==0) return true;
len=j;
}
}
return false;
}
};
Solution 2(C++)
class Solution {
public:
bool canJump(vector<int>& nums) {
int reach = 0;
for (int i = 0; i < nums.size(); i++){
if (i > reach){
return false;
}
reach = max(reach, i + nums[i]);
}
return true;
}
};
算法分析
解法一是自己写的,没有TLE,思路也挺简单的,就是从后往前判断,用len记录要到达的位置,那么如果有nums[j] >= len-j,说明能从j这个位置调到len这个位置。然后更新len与j,一直到j=0,说明找到了一条可以通往最开始len的位置。如果遍历了整个数组都没有找到,那么就说明没有找到这样的一条路径,返回false。
解法二是利用贪心算法,每到一个点,就记录能到达的最大位置,如果一个位置i超过了能到达的最大位置reach,那么就说明不能到达i这个地方,i以后的地方也没有办法到达。返回false。如果一直遍历到nums.size()-1,那么就说明能到达结尾,返回true。reach的更新方法自然是取当前reach与i+nums[i],表示从i这个点最大跳nums[i]的距离,能到达的地方。
程序分析
略。