码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Jump Game II

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

标签:style   blog   http   color   os   io   for   ar   

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

标签:style   blog   http   color   os   io   for   ar   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!