问题描述:
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
.
解题思路:
该题的意思是nums[i]是能跳的最大数值,两个元素间隔为1.故可以用贪心,每次都求能跳的最大看是否能跳到n-1。
class Solution{
public:
bool Canjump(vector<int> &nums){
if(nums.empty()) return false;
int maxstep=nums[0];
int len=nums.size();
for(int i=1;i<len;i++)
{
return false;
else if(maxStep<0)
return false;
else{
maxStep=max(--maxStep,nums[i]);
}
}
return true;
}
}