问题描述:
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
.
解析:该问题只需要考虑0值点的情况,因为0值点才有可能出现跳不到下一个点,另外当最后一个点为0点时,不需要考虑,当遇到0点时,只需要查看该点前是否有足够大的点的步数能够跳过该点,若不能,则世界结束,若能,则继续遍历;
代码:
class Solution {
public:
bool canJump(vector<int>& nums) {
int numsLength = nums.size(),currentIndex=0,currentMaxStep = 0,over = 0;//数组的长度,current表示当前的位置,从0开始,currentMaxStep表示当遇到0时能否通过该点,over表示当0点是否可以跳过
while(currentIndex < numsLength – 1 && over == 0 ){//考虑前numsLength – 1的点
if(nums[currentIndex] == 0){//当遇到0点
for(int i = 0;i < currentIndex;i++){
if(nums[i] >= currentIndex – i + 1){//判断在该0点之前是否有可以跨过该0点的值
currentMaxStep = 1;
}
}
if(currentMaxStep == 0){当该0点无法跳过时,循环结束,存在时currentMaxStep = 1,表示该点可以跳过
over = 1;
}else{
currentIndex++;
currentMaxStep = 0;
}
}else{
currentIndex++;
}
}
if(currentIndex != numsLength – 1)//循环结束后判断是否调到最后一点
return false;
else
return true;
}
};