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

由于每层最多可以跳{A[i]}步,也可以跳0或1步,因此如果能到达最高层,则说明每一层都可以到达。有了这个条件,说明可以用贪心法。

从0出发,一层一层网上跳,看最后能不能超过最高层,能超过,说明能到达,否则不能到达。

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int reach =1;
        for(int i =0; i < reach && reach<nums.size(); i++)
        {
              reach = max(reach, i+1+nums[i]);
        }
        return reach>=nums.size();
    }
};



你可能感兴趣的:(【LeetCode】55. Jump Game)