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];
        }
    }
  • 相关阅读:
    oc 基本基础类型之NSString
    oc 内存管理
    自定义的init方法和重写的init方法
    property属性
    iOS 开发朗读文字
    获取当前最顶层的ViewController
    二维码扫描的简单封装
    OC百度导航类的封装
    OC上传图片的封装(配合AFNetWorkiing)
    集成百度地图报错41个解决方法(转)
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3732352.html
Copyright © 2011-2022 走看看