LeetCode 55. 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.

 


题目标签:Array

  这道题目给了我们一个array,其中每一个数字代表着可以跳跃的最大步数,让我们判断,能不能跳跃到最后一个数字,这里没有要求要刚刚好跳到最后,超过也可以。一开始自己写了一个递归方法,但是因为速度慢,无法通过全是1的array。所以这道题目用Dynamic Programming方法,遍历array,过程中,我们只需要维护一个值 - 最远能跳跃到的地方 farthestNumIndex。对于每一个数字,我们都算一下它能最远跳跃到哪里,然后和 我们维护的 farthestNumIndex 比较,取大的。所以当我们知道了我们最远能够跳跃到哪里的话,如果遇到了原题中的第二种可能,怎么也跳跃不过0的这种情况,我们只需要判断目前的数字的index i 是不是超过了 farthestNumIndex,超过了,就直接判断为false了。 当farthestNumIndex 达到了,或者超越了最后一位数字的 index,就判断true。

 

 

Java Solution:

Runtime beats 39.82% 

完成日期:07/19/2017

关键词:Array

关键点:Dynamic Programming - 维护一个跳跃到最远的值

 

 1 public class Solution 
 2 {
 3     public boolean canJump(int[] nums) 
 4     {
 5         int farthestNumIndex = 0; // the farthest place we can jump to
 6         boolean res = false;
 7         
 8         for(int i=0; i<nums.length; i++)
 9         {
10             if(i > farthestNumIndex) // meaning there is no way to jump further
11                 break;
12             
13             if(farthestNumIndex >= nums.length - 1) // meaning we can jump to or over the last number
14             {
15                 res = true;
16                 break;
17             }
18             // keep tracking the farthest spot we can jump
19             farthestNumIndex = Math.max(farthestNumIndex, i + nums[i]);
20         }
21 
22         return res;
23     }
24     
25 }

参考资料:

http://www.cnblogs.com/grandyang/p/4371526.html

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

posted @ 2017-07-20 05:47  Jimmy_Cheng  阅读(401)  评论(0编辑  收藏  举报