55. Jump Game
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
.
题目链接:https://leetcode.com/problems/jump-game/description/
题目大意:给定一个数组,每个数字代表当前可向后走的最大步数。从第一个数字开始,求是否能走到最后一个数字位置,若能,返回true,否则返回false。
解题思路:纪录当前能走的最大步数,即从前一步的最大步数减一和当前下标对应步数中选择最大的一个,如果最大步数非零,向前走一步,直到走到最后一个数字。
代码如下:
class Solution {
public:
bool canJump(vector<int>& nums) {
int n = nums.size();
int i = 0;
int cur = nums[0];
while(i < n - 1){
cur = max(cur - 1,nums[i]);
if(cur >= 1)
i ++;
else if(cur == 0 && i <= n-2){
return false;
}
}
return true;
}
};