Leetcode 55 Jump Game

2018-01-12 15:03:41 浏览数 (1)

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.

和之前用最少步数跳到终点的方法一样,贪心!

https://cloud.tencent.com/developer/article/1019282

如果能够跳到终点,则用最小步数的试探方法一定能够到达终点!

代码语言:javascript复制
class Solution {
public:
    bool canJump(vector<int>& nums) {
        int st=0;
        while(st<nums.size()-1)
        {
            int maxx=-1,pos;
            for(int i=1;i<=nums[st];i  )
            {
                if(i nums[st i]>=maxx)
                {
                    maxx=i nums[st i];
                    pos=i;
                }
            }
            if(maxx==-1) return false;
            st =pos;
        }
        return true;
    }
};

0 人点赞