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

    这道题目跟第一道题目有区别,如果用DP动态规划来解决的话,会出现超时的问题。。也有可能是自己用的不好,后面发现一种线性遍历获得最小步骤的方法

    DP 没有被AC

    public class Solution {
        public int jump(int[] A) {
            if(A.length==0)
                return 0;
            if(A[0]>=A.length)
                return 1;
            int[] step = new int[A.length];
            Boolean[] bol = new Boolean[A.length];
            
            step[0]=0;
            bol[0]=true;
            for(int i=1;i<A.length;i++){
                bol[i]=false;
                step[i]=0;
                for(int j=0;j<i;j++){
                    if(bol[j]&&(A[j]+j)>=i){
                        bol[i]=true;
                        if((A[j]+j)>=A.length-1)
                            return step[j]+1;
                        int temp = step[j]+1;
                        if(step[i]==0){
                            step[i]=temp;
                        }else{
                            
                            if(step[i]>temp)
                                step[i]=temp;
                        }
                    }
                }
            }
            return step[A.length-1];
            
        }
    }

    线性时间AC、

    public class Solution {
        public int jump(int[] A) {
            if(A.length==0)
                return 0;
            if(A.length==1){
                return 0;
            }
                
            int[] step = new int[A.length];
            step[0]=0;
            int cur =0;
            Arrays.fill(step, 0);
            for(int i=0;i<A.length;i++){           
                int temp = i+A[i];
                if(temp>=A.length-1){
                    return step[i]+1;
                }
                for(int j=cur+1;j<=temp;j++){
                    step[j]=step[i]+1;
                }
                if(temp>=cur)
                    cur=temp;
            }
            return step[A.length-1];
        }
    }
  • 相关阅读:
    Django跨域问题
    DOM,jquery,vue
    from和modelform的用法和介绍
    元类的__call__和__new__方法的作用
    Django学习之路由分发和反向解析
    Django 自定义auth_user
    Django创建对象的create和save方法
    Flask--(登录注册)抽取视图函数
    Flask--(项目准备)--添加日志
    Flask--(项目准备)--框架搭建,配置文件抽取,业务逻辑抽取
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3752398.html
Copyright © 2011-2022 走看看