Jump Game

来源:互联网 发布:苏州餐饮软件sjzpos 编辑:程序博客网 时间:2024/05/29 03:56

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.


Solution:

class Solution {public:    bool canJump(vector<int>& nums) {        int len = nums.size();        if(len <= 1) return true;        int start = 0, far = nums[0];        while(start < len)        {            if(start == far)            {                if(!nums[start]) return false;                else                {                    far += nums[start];                    if(far >= len - 1) return true;                }            }            else            {                far = max(far, start + nums[start]);                if(far >= len - 1) return true;            }            start++;        }    }};


0 0