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;
    }
  • 相关阅读:
    Nmap 網路診斷工具基本使用技巧與教學
    你必须了解的基础的 Linux 网络命令
    SQLAlchemy 一对多
    Linux统计文件行数
    网络拥塞控制(三) TCP拥塞控制算法
    JavaSe:Properties文件格式
    ZooKeeper:第三方客户端 ZKClient
    ab
    JDWP Agent
    ZooKeeper:数据模型
  • 原文地址:https://www.cnblogs.com/joannacode/p/4413485.html
Copyright © 2011-2022 走看看