第五周:[Leetcode]55. Jump Game

来源:互联网 发布:淘宝怎么生成数据包 编辑:程序博客网 时间:2024/05/16 08:31

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.


维护一个变量up,记录目前所能到达的最远的数组下标,若up大于等于最后的数组下标,则成功,否则失败。


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