leetcode_question_55 Jump Game

来源:互联网 发布:淘宝客怎么做推广 编辑:程序博客网 时间:2024/05/10 09:05

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(int A[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(n <= 1) return true;        int index = 0;        while(index < n)        {            if(index == n-1) return true;            if(A[index] == 0)return false;            index += A[index];        }        return true;    }};

上面这几行代码有问题,当时题意理解不到位写的代码,是不对的,但是,但是在leetcode上面Judge Small和Judge Large都通过,有木有!!!


ooo:

bool canJump(int A[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(n<2) return true;        int jump = 0;        for(int i=0; i < n-1; ++i,--jump)        {            jump = max(jump,A[i]);if(jump <= 0) return false;        }        return true;    }};



原创粉丝点击