55. Jump Game

来源:互联网 发布:windows to go u盘 编辑:程序博客网 时间:2024/06/07 18:48

problem:

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.

之前做过jump game ii,那题需要记录最少步数,这题和那题类似,但是要记录是否能挑到最后一位。所以这题简单一点,因为不用管是不是最短,能够在距离范围内就行。也是记录当前位置能到达的最远距离。

class Solution {public:    bool canJump(vector<int>& nums) {        if(nums.size() <= 0)            return false;        if(nums.size() == 1)            return true;        int pos=0;        int reach = 0;//记录当前位置能跳到的最远距离        while(pos < nums.size()-1)        {            if(pos <= reach)            {                reach = max(reach, pos+nums[pos]);                pos++;            }            else                return false;        }        if(reach >= nums.size()-1)            return true;        else            return false;    }};



0 0