LeetCode-55. 跳跃游戏 (中等)
题目地址:https://leetcode-cn.com/problems/jump-game/
1. 题目描述及示例
给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个下标。
示例一
输入: nums = [2,3,1,1,4]
输出: true
解释: 可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
示例二
输入: nums = [3,2,1,0,4]
输出: false
解释: 无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
2. 题解和代码实现
典型的贪心算法的实现。在这里,定义所能到达的最远位置farthest,根据每一步来进行更新所能到达的最远位置。所以应该有以下步骤:
- farthest > i 是否成立,当该式成立时代表能够往下面进行跳跃,不成立时代表到该点应该进行终止。
- farthest = max(i+nums[i],farthest),进行更新farthest。
代码实现(C++ 2022-3-25)
class Solution {
public:
bool canJump(vector<int>& nums) {
int farthest = nums[0];
int length = nums.size();
for(int i=1;i<length;i++){
if(farthest>=i){ // 能跳到该位置
if(nums[i]+i>farthest){
farthest = nums[i]+i; // 更新能够跳的最远位置
}
}else{
return false;
}
}
return true;
}
};
3. 总结
2022-3-25进行实现该代码。