zoukankan      html  css  js  c++  java
  • 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.)

    自己写的,超时了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;
    }
  • 相关阅读:
    BZOJ 2653 middle
    BZOJ 3207 花神的嘲讽计划Ⅰ
    BZOJ 3689 异或之
    BZOJ 3037 创世纪
    BZOJ [1264] [ AHOI2006]基因匹配Match
    BZOJ 2186 [Sdoi2008]沙拉公主的困惑
    BZOJ 3362 Navigation Nightmare
    BZOJ 3209 花神的数论题
    BZOJ 1411 ZJOI2009 硬币游戏
    【HDU1573】X问题
  • 原文地址:https://www.cnblogs.com/joannacode/p/4413485.html
Copyright © 2011-2022 走看看