LeetCode 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.

Example 1:

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:

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.

解答:

经典的贪心算法,也就是每一步都求最优解,所有的最优解组合就可以得到整个问题的最优解。这道题关心的是最左边的格子能否到达最右边的格子,我们不妨从右到左来分析,设最右边格子的index为lastPos,如果倒数第二个格子可以到达lastPos,那么更新lastPos为倒数第二个格子的index,以此类推,如果最后可是似的lastPos为第一个格子的index,也就是你说明该可以从最左边到达最右边

代码如下:

 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)

空间复杂度:O(1)

参考链接:

https://leetcode.com/problems/jump-game/solution/

原文地址:https://www.cnblogs.com/dapeng-bupt/p/10349773.html