凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 55. Jump Game

分类:algorithm| 发布时间:2017-01-10 23:48:00


题目

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.

题意

给出一个非负数组,数组的数字表示你能走多远,判断你能否从队头走到队尾。

解法

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int next = 0;
        int i = 0;
        for(; i < nums.size() && i <= next; ++i) {
            next = max(next, i + nums[i]);
        }

        return i == nums.size();
    }
};