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
.
贪心算法可以搞定,复杂度O(n),比较容易
class Solution {
public:
bool canJump(vector<int>& nums) {
vector<int>::size_type idxFarest = 0;
for(vector<int>::size_type iLoop = 0; iLoop < nums.size(); iLoop++){
if(iLoop > idxFarest)
return false;
if(iLoop + nums[iLoop] > idxFarest){
idxFarest = iLoop + nums[iLoop];
}
}
return idxFarest >= (nums.size() - 1) ;
}
};