首页 > 其他 > 详细

[leetcode]Jump Game II

时间:2014-08-08 01:51:45      阅读:289      评论:0      收藏:0      [点我收藏+]

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.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

算法思路:

[leetcode]Jump Game类似,不过数组不仅仅记录可达性,要记录最短路由跳数。思想一样。

例如[25000,24999,24998,24997,24996,24995,24994,24993......1]这个栗子,如果不记录最远可达(approach)的话,重复计算,势必超时

代码如下:

 1 public class Solution {
 2     public int jump(int[] a) {
 3         if(a == null || a.length < 2) return 0;
 4         int[] step = new int[a.length];
 5         for(int i = 1; i < a.length; i++){
 6             step[i] = a.length;
 7         }
 8         int approach = 0;
 9         for(int i = 0; i < a.length; i++){
10             int cover = i + a[i];
11             if(cover <= approach) continue;
12             for(int j = approach; j <= Math.min(cover,a.length - 1); j++){
13                 step[j] = Math.min(step[i] + 1,step[j]);
14             }
15             approach = i + a[i];
16         }
17         return step[a.length - 1];
18     }
19 }

 

[leetcode]Jump Game II,布布扣,bubuko.com

[leetcode]Jump Game II

原文:http://www.cnblogs.com/huntfor/p/3898462.html

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