55. Jump Game

来源:互联网 发布:比思论坛2017最新域名 编辑:程序博客网 时间:2024/06/07 12:47

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.

Subscribe to see which companies asked this question.

惯例翻译题目:这题比较简单,给你一个数组,里面每个元素表示你可以向后跳跃的步数,我们需要知道

能不能移动到最后一个元素位置;

采用贪心法即可,譬如上面的[2, 3, 1, 1, 4],因为初始第一个位置为2,我们先跳1步,剩下1步了,到第二

个元素位置,也就是3这个地方,因为3比1大,所以我们可以向后面跳跃3步,直接就到4了;

根据上面的规则,每次跳跃1步,我们可跳跃步数减1,如果新的位置步数大于剩余步数,使用新的步数继

续移动,如果可跳跃次数小于0并且还没到最后一个元素,那么失败。

代码如下:

class Solution {
public:
bool canJump(vector<int>& nums) {
    int n=nums.size();
    if(n == 0) {
        return true;
    }
    int v = nums[0];
    for(int i = 1; i < n; i++) {
        v--;
        if(v < 0) {
            return false;
        }
        if(v < nums[i]) {
            v = nums[i];
        }
    }
    return true;
    }
};