题目:
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
.
思路:
采用贪心算法,每到一个位置就计算随后能到达的位置的范围,然后向后走一步,如果发现不能到达目前这个位置,或者走到最后一步时范围不能覆盖终点则返回false,否则返回true。
程序:
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size() == 0)
return 0;
int maxPos = 0;
for(int i = 0;i < nums.size() - 1;i++)
{
if(maxPos < i)
return false;
maxPos = max(maxPos,i + nums[i]);
}
if(maxPos >= nums.size() - 1)
return true;
else
return false;
}
};