zoukankan      html  css  js  c++  java
  • 45. Jump Game II

        /*
         * 45. Jump Game II 
         * 12.5 by Mingyang
         * 一开始的做法是用的自己的代码,DP思想,始终是n的平方,最终时间超出了
         * 感觉应该不会有问题,除了一开始没考虑0这个值
         */
        public static int jump11(int[] nums) {
            int len=nums.length;
            if(nums==null||len==0)
              return 0;
            int[] dp=new int[len];
            dp[len-1]=0;
            for(int i=len-2;i>=0;i--){
                if(nums[i]>=len-1-i){
                    dp[i]=1;
                }else{
                    if(nums[i]==0)
                        dp[i]=Integer.MAX_VALUE;
                    int min=Integer.MAX_VALUE;
                    for(int j=i+1;j<=i+nums[i];j++){
                        if(dp[j]>0){
                            dp[i]=Math.min(dp[j]+1,min);
                            min=dp[i];
                        }
                    }
                }
            }
            if(dp[0]!=Integer.MAX_VALUE)
            return dp[0];
            else
            return 0;
        }
        /*
         * 下面就是大神的代码
         * 这道题是Jump Game的扩展,区别是这道题不仅要看能不能到达终点,而且要求到达终点的最少步数。
         * 其实思路和Jump Game还是类似的,只是原来的全局最优现在要分成step步最优和step-1步最优(假设当前步数是step)。
         * 当走到超过step-1步最远的位置时,说明step-1不能到达当前一步,我们就可以更新步数,将step+1。时间复杂度仍然是O(n),空间复杂度也是O(1)
         */
        public static int jump(int[] A) {
            if (A == null || A.length == 0)
                return 0;
            int maxcover = 0;
            int step = 0;
            int lastcover = 0;
            for (int i = 0; i <= maxcover && i < A.length; i++) {
                if (i > lastcover) {
                    step++;
                    System.out.println("Jumpat index:" + i);
                    lastcover = maxcover;
                }
                if (A[i] + i > maxcover)
                //不断更新最远的距离,能到达的最远距离
                    maxcover = A[i] + i;
            }
            if (maxcover < A.length - 1)
                return 0;
            return step;
        }
  • 相关阅读:
    LeetCode: Reverse Linked List
    DataBase: MySQL在.NET中的应用
    DataBase: LeetCode
    DirectShow+VS2010+Win7配置说明
    MathType应用:批量改变公式格式
    $LaTeX$笔记:首字下沉
    Latex学习笔记-序
    反思--技术博客的写作应该是怎样的?
    用Latex写学术论文:作者(Author)&摘要(Abstract)
    用Latex写学术论文: IEEE Latex模板和文档设置(documentclass)
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5464930.html
Copyright © 2011-2022 走看看