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

Jump Game II

时间:2015-04-10 08:19:10      阅读:109      评论: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.

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

自己写的,超时了QAQ,就说hard的题怎么可能这么简单T_T。

package leetcode2;

public class jumpgame2 {
    public static int jumpgame(int[] A){
        int count=0;
        if(A[0]==0){
            return 0;
        }
        int i=0;
        while(i<A.length-1){
            int maxstep=i+1;
            int max=0;
            for(int j=1;j<A[i];j++){
                if(i+j<A.length-1){
                if(A[i+j]>=max){
                    max=A[i+j];
                    maxstep=j+i;
                }
                }else{
                    return count+1;
                }
            }
            i=maxstep;
            count++;
        }
        return count;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
       int[] a={2,5,1,1,4};
       System.out.print("result is "+jumpgame(a));
    }

}

正确代码:dp

public int jump(int[] A) {
    if(A==null || A.length==0)
        return 0;
    int lastReach = 0;
    int reach = 0;
    int step = 0;
    for(int i=0;i<=reach&&i<A.length;i++)
    {
        if(i>lastReach)
        {
            step++;
            lastReach = reach;
        }
        reach = Math.max(reach,A[i]+i);  //A[i]+i是最大能到的下一步!!
    }
    if(reach<A.length-1)
        return 0;
    return step;
}

 

Jump Game II

标签:

原文地址:http://www.cnblogs.com/joannacode/p/4413485.html

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