题目:
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
.
解答:
直接贪心的思路,不断的更新可以到达的位置的最右边界即可
class Solution {
public:
bool canJump(vector<int>& nums) {
int limit = nums[0];
int size = nums.size();
int pos = 0;
while(pos < size && pos <= limit)
{
pos++;
if(pos <= limit && nums[pos] + pos > limit)
limit = nums[pos] + pos;
}
return (limit >= size - 1);
}
};