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.spa
Determine if you are able to reach the last index.code
Example 1:blog
Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:element
Input: [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
解答:leetcode
经典的贪心算法,也就是每一步都求最优解,全部的最优解组合就能够获得整个问题的最优解。这道题关心的是最左边的格子可否到达最右边的格子,咱们不妨从右到左来分析,设最右边格子的index为lastPos,若是倒数第二个格子能够到达lastPos,那么更新lastPos为倒数第二个格子的index,以此类推,若是最后但是似的lastPos为第一个格子的index,也就是你说明该能够从最左边到达最右边get
代码以下:it
1 class Solution { 2 public: 3 bool canJump(vector<int>& nums) { 4 int lastPos = nums.size() - 1; 5 for (int i = nums.size() - 1; i >= 0; i--) 6 if (nums[i] + i >= lastPos) 7 lastPos = i; 8 return lastPos == 0; 9 } 10 };
时间复杂度:O(N)io
空间复杂度:O(1)ast
参考连接: