55. Jump Game (leetcode)

来源:互联网 发布:通达信期货软件 编辑:程序博客网 时间:2024/05/12 16:14

题目地址
https://leetcode.com/problems/jump-game/

题目描述

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.


采用动归 或者 递归等都会超时

此题维持一个最右边可以到达的位置,判断即可

ac代码如下,注意逻辑,语句顺序不一致也可能错误

class Solution {public:    bool canJump(vector<int>& nums) {        int len = nums.size();        if (len == 1)            return true;        int imax = nums[0];        int i = 1;        while (i < len)        {            if (imax >= len - 1)                return true;            if (i > imax)                break;            if (i + nums[i] <= imax)            {                i++;                continue;            }            else            {                imax = i + nums[i];            }            i++;        }        return false;    }};
0 0
原创粉丝点击