LeetCode第[55]题(Java):Jump Game

题目:跳跳游戏

难度:Medium

题目内容

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.

翻译

给定一个非负整数数组,您最初被定位在数组的第一个索引中。

数组中的每个元素代表您在该位置的最大跳跃长度。

确定你是否能够到达最后一个索引。

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: 第一步,跳2步到索引2,第二步跳1步到索引3,第三步跳1步到索引4,到达
        第一步,跳1步到索引1,第二步跳3步到索引4,到达

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: 无论如何,你总是会到达索引3。它的最大跳转长度为0,这使得到达最后一个索引是不可能的。

我的思路:不知道咋做。。。

答案代码

1 public boolean canJump(int[] A) {
2     int max = 0;
3     for(int i=0;i<A.length;i++){
4         if(i>max) {return false;}
5         max = Math.max(A[i]+i,max);
6     }
7     return true;
8 }

答案思路:因为所跳的步数能从0到A[ i ] 都行所以只要前面能达到的最远下标的最大值能大于后面的下标,就表示能跳到,否则跳不到。能达到的最远下标为A[i] + i 。

eg.:[3,2,1,0,4

前面三个的能达到的最远下标最大值为3,所以此时最远只到下标3,而下标3的最远下标是自己,到了下标4进行判断发现前面的最远下标比自己的下标小,所以跳不到。

猜你喜欢

转载自www.cnblogs.com/Xieyang-blog/p/9032983.html