题目描述:
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.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
Tags: Array Greedy
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.
Tags: Array Greedy
分析:这是一个动态规划类型的。要判断是否能到达最后一个位置,那么只需一次计算出每个位置能达到的最远位置,如果其中一个最远位置能到达,那就返回true。
/**20ms*/
class Solution {
public:
bool canJump(vector<int>& nums) {
int len = nums.size();
if(len == 0 || len == 1)
return true;
int max = nums[0]; //初始化当前位置往前能到达的最远距离
for(int i = 1; i < len; i++){
if (max == 0) //当前不能跳了
return false;
max--; //下标加1后,在上一个位置的基础上,当前位置能往前移动的最远距离要减1
if(max < nums[i]) //更新当前位置能到达的最远位置
max = nums[i];
if(max + i >= len-1) //判断移动后是否到达最后的位置
return true;
}
}
};