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];
        }
    }
  • 相关阅读:
    [Tutorial] How to check and kill running processes in Ubuntu
    [Tutorial] Getting started with Gazebo in ROS
    Linux基础命令
    Linux安装系统
    vue 前后端数据交互问题解决
    如何在cmd中启动MongoDB服务器和客户端
    selenuim模块的使用 解析库
    beautifhulsoup4的使用
    浅谈scrapy框架安装使用
    自动登录 点赞 评论 抽屉网
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3732352.html
Copyright © 2011-2022 走看看