leetcode---jump-game---贪心

来源:互联网 发布:cf数据异常23 0 编辑:程序博客网 时间:2024/06/05 17:46

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], returntrue.
A =[3,2,1,0,4], returnfalse.

class Solution {public:    bool canJump(int A[], int n)     {        if(n == 0)            return true;        int step = A[0];        int cur = 0;        while(step > 0)        {            int maxStep = step;            int id = cur;            for(int i=cur+1; i < n && i<=cur+step; i++)            {                if(maxStep < A[i])                {                    maxStep = A[i];                    id = i;                }            }            cur = id + maxStep;            if(cur >= n-1)                return true;            step = A[cur];        }        return cur >= n-1;    }};
原创粉丝点击