55. Jump Game

来源:互联网 发布:java游戏开发主程 编辑:程序博客网 时间:2024/06/07 06:45

题目: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.

给出一个全是非负整数的数组,初始情况下你在数组的第一个元素的下标。
数组每个下标对应的元素表示你能向后移动的最大长度,判断是不是能够移动到数组的最后一个元素的下标上。

例:
A = [2,3,1,1,4], 可以从下标0移动到下标1,再从下标1移动到下标4,返回true。
A = [3,2,1,0,4], 最多只能移动到下标3,无法移动到下标4,返回false。

思路

假设当前的下标是 i,对应的元素为nums[ i ],那么从 i 到 i + nums[ i ]的下标都是可达的。
用一个maxLen表示当前可以到达的最远距离,初始是0,用 i 表示当前走到的下标,初始也是0.
对于 i 所处的下标位置,用i + nums[i]和maxLen比较来取大者,用来能更新走到的最远距离。
当 i 没有走到数组的终点并且 i 没有超出走的最远的距离时,让i++。
此外,当manLen超过数组的长度时表示肯定可以走到数组的重点,可以直接判断为true。
当i走出循环时,判断是不是在最后一个下标位置上,是的话说明可以走到终点,不然就不可以。

参考代码

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