55. Jump Game

来源:互联网 发布:人脸变老软件电脑版 编辑:程序博客网 时间:2024/04/30 13:54

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.

思路:每次记录当前位置可以到达的最远的位置,如果当前位置的index一直小于等于这个最远值就证明可以一直走下去,如果index可以走到尾部就证明是可达的。

class Solution {public:    bool canJump(vector<int>& nums) {        int reach = 0, i = 0;        for(; i < nums.size() && i <= reach; i++)        {            reach = max(reach, i + nums[i]);        }        return i==nums.size();    }};
0 0
原创粉丝点击