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

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

思路:

参考别人的思路,贪心算法。

结合自己的乱七八糟的思路:

  • 用索引i来记录当前位置。
  • 用maxIndex记录从i能到的最远位置。
bool canJump(vector<int>& nums) {
        
        int n = nums.size();
        int maxIndex = 0;
        
        for(int i = 0;i < n;i++)
        {
           if(i<=maxIndex) maxIndex = max(maxIndex,i+nums[i]);            
        }
        
        return maxIndex>=n-1;
    }

参考:

https://oj.leetcode.com/discuss/15567/linear-and-simple-solution-in-c

http://www.xuebuyuan.com/1388053.html

原文地址:https://www.cnblogs.com/hellowooorld/p/6538862.html