题目
给定一个非负整数数组 nums
,你最初位于数组的 第一个下标 。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
示例 1:
输入:nums = [2,3,1,1,4]
输出:true
解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
示例 2:
输入:nums = [3,2,1,0,4]
输出:false
解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
提示:
1 <= nums.length <= 3 * 10^4
-
解题方法
动态规划
使用
dp
表示当前节点是否能到达末尾节点,使用target
记录上一个能够到达末尾元素的下标。采用反向递推,有如下递推关系:
时间复杂度O(n)
,空间复杂度O(1)
C++代码:class Solution { public: bool canJump(vector<int>& nums) { int target = nums.size()-1; bool dp = true; for(int i=target-1; i>=0; i--) { if(nums[i]>=(target-i)) { dp = true; target = i; } else dp = false; } return dp; } };
贪心
使用
mostright
维护能够到达的最远点,遍历各节点,如果i < mostright
,则对mostright
进行更新,即mostright = max(nums[i]+i, mostright)
。
时间复杂度O(n)
,空间复杂度O(1)
class Solution { public: bool canJump(vector<int>& nums) { int n = nums.size(); int mostrigh = 0; for(int i=0; i<n; i++) { if(i<=mostrigh) mostrigh = max(nums[i]+i, mostrigh); if(mostrigh>=n-1) return true; } return false; } };