首页 > 其他 > 详细

LeetCode: Jump Game II

时间:2014-03-16 14:13:38      阅读:505      评论:0      收藏:0      [点我收藏+]

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.

Your goal is to reach the last index in the minimum number of jumps.

 

最开始想像jump game I一样用动态规划,发现会超时。

所以想到了用贪心算法。

可以计算每一步可以跳到的最远距离。第一次到达数组末尾时就是最少的steps。时间复杂度为O(n).

bubuko.com,布布扣
 1 public static int jump2 (int[] A) {
 2         if (A.length == 0) return -1;
 3         int steps = 0;
 4         int index = 0;
 5         int last = -1;
 6         
 7         while (index < A.length-1) {
 8             int l = index;
 9             for (int i = index; i > last; i--) {
10                 if (i + A[i] > l) l = i + A[i];
11             }
12             if (index == l) return -1;
13             last = index;
14             index = l;
15             steps++;
16         }
17         
18         return steps;
19     }
bubuko.com,布布扣

也可以计算,在每个点的时候能跳到的最远的距离。第一次到达末尾时,是最少的steps。

last记录的是上一次能跳到的最远的距离。只有当i超过last的时候,说明已经超过了上一次跳跃的最大距离,是又发生了一次跳跃。所以steps++。

bubuko.com,布布扣
 1 public int jump(int[] A) {
 2         int steps = 0;
 3         int index = 0;
 4         int last = -1;
 5         
 6         for (int i = 0; i < A.length; i++) {
 7             
 8             if (index >= A.length - 1) {
 9                 break;
10             }
11             if (i > last) {
12                 steps++;
13                 last = index;
14             }
15             if (i + A[i] > index) {
16                 
17                 index = i + A[i];
18             }
19         }
20         
21         return steps;
22     }
bubuko.com,布布扣

LeetCode: Jump Game II,布布扣,bubuko.com

LeetCode: Jump Game II

原文:http://www.cnblogs.com/longhorn/p/3603013.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!