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.
思路:
比如说第一个例子,第一个数字是2,能到达的最远的位置是第三个位置,在这个范围内(1-3),第二个数字3能到达的最远位置是第五个位置,则更新当前能到达的最远位置为5。如果能到达的最远位置不是最后一个位置,并且其数值为0,那么返回false,表示永远不会到达最后的位置,否则返回true。
代码:
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size()==1) return true;
int curr = nums[0];
for(int i=0; i<nums.size(); i++){
if(nums[i]+i > curr){
curr = nums[i]+i;
}
if(curr == i){
if(nums[i] == 0 && i!= nums.size()-1) return false;
continue;
}
}
return true;
}
};