Given an array of non-negative integers, you are initiallypositioned at the first index of the array.
Each element in the array represents your maximum jump length atthat 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
这题给你一个数组,问你从第一位置开始是否能够到达数组的最后一个位置,
设置两个指针left和right,当0~right表示一定可以到达的索引集合,最开始right=0,
然后不断的向右移动left,当nums[left]+left>right,的时候,说明right右边有新的区域被确定为可以到达,因此设置right=nums[left]+left,当nums[left]+left>=n-1的时候,说明数组的最后一个位置已经被确定为可以到达了,返回true,当left>right,的时候,说明right之后的位置都不能到达了,返回false
class Solution {
public:
bool canJump(vector<int>& nums) {
int n = nums.size();
int left = 0, right = 0,l;
while (left <= right)
{
l = nums[left] + left;
if (l >= n - 1) return true;
if (l > right) right = l;
left++;
}
return false;
}
};