LeetCode: Jump Game II

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).

 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     }

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

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

 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     }

 

posted on 2014-03-16 09:07  longhorn  阅读(163)  评论(0编辑  收藏  举报

导航