55. Jump Game

思路:

对于数列里的每一个数,从头到尾扫一遍,每一个位置上的数能够达到最远的地方,就是这个位置加上这个位置可以走的最远的位置。

再维持一个目前为止的最大值,如果目前的位置已经超过了曾经有过的最大的值,那么就结束,返回false。

如果全局的最大值已经能够达到数列的末尾,那么就返回true。

 

 1     public boolean canJump(int[] nums) {
 2         if(nums == null || nums.length == 0) {
 3             return false;
 4         }
 5         if(nums.length == 1) {
 6             return true;
 7         }
 8         int[] res = new int[nums.length];
 9         res[0] = nums[0];
10         int max = nums[0];
11         for(int i = 1; i < nums.length; i++) {
12             if(i > max) {
13                 break;
14             }
15             res[i] = nums[i] + i;
16             max = Math.max(res[i], max);
17             if(max >= nums.length - 1) {
18                 return true;
19             }
20         }
21         return false;
22     }

 

posted @ 2016-03-04 04:36  warmland  阅读(149)  评论(0编辑  收藏  举报