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;
}
};
本文介绍了一个经典的编程问题——Jump Game。任务是从数组的第一个元素出发,根据每个元素的数值决定可以跳跃的最大长度,判断是否能够到达数组的末尾。文章提供了一种有效的解决方案,并附带了详细的实现代码。
696

被折叠的 条评论
为什么被折叠?



