leetcode No55. Jump Game

来源:互联网 发布:阿里云ecs sn型号 编辑:程序博客网 时间:2024/05/19 05:31

Question:

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.

题目大意是每个元素代表能往下走的最大距离,判断是否能走到最后一个元素

Algorithm:

贪心算法,一直找能找到的最大距离,如果到最后最大距离包含最后一个元素即证明能走到

Accepted Code:

class Solution {   //greedypublic:    bool canJump(vector<int>& nums) {        int maxJump=-1;        int N=nums.size();        if(N<=0)return false;        for(int i=0;i<N;i++)        {            if(nums[i]>maxJump)                maxJump=nums[i];            if(maxJump>=(N-i-1))                return true;            if(maxJump==0)                return false;                            maxJump--;  //左移一步,maxJump需要减1        }        return false;    }};


0 0