给定一个数组,判断从开始能否走到结束,最多需要几步?

1、给定一个非负数组,数组中的元素代表从当前位置可以向后跳几步,判断能否走到数组末尾。例如:A = [2,3,1,1,4], return true;A = [3,2,1,0,4], return false.

public boolean canJump(int[] nums) {
        int maxIndex = nums.length-1;
        int maxJump  = nums[0];
        for(int i = 0; i <= maxJump; i++){
            maxJump=Math.max(maxJump,i+nums[i]);
            if(maxJump>=maxIndex) return true;
        }
        return false;
    }

2、求出从数组开始到末尾最少可以跳几次。例如:A = [2,3,1,1,4],则最少需要2步,2–>3–>4。

2.1、最直观,递归

     public int jump(int[] nums) {
          if(nums.length==1)return 0;
          return  getLen(nums,0);
     }
     public int getLen(int []nums,int i){
         if(i>=nums.length-1)return 0;
         int val=nums[i];
         int min=nums.length;
         for(int j=i+1;j<=i+val;j++){
             min=Math.min(getLen(nums,j),min);
         }
         return min+1;
     }

2.2、动态规划,保存之前求过的值

    public int jump(int[] nums) {
       if(nums.length==1)return 0;
       int dp[]=new int[nums.length];
       int temp=0,len=nums.length;
       for(int i=len-2;i>=0;i--){
           temp=nums[i];
           dp[i]=len;
           temp+=i;
           for(int j=i+1;j<=temp&&j<len;j++){
               dp[i]=Math.min(dp[i],dp[j]);
           }
           dp[i]++;
       }
       return dp[0];

2.3、维持两个指针,一个表示当前最远可以跳到哪一步,一个表示下一步最远可以跳到哪一步。遍历原数组同时更新指针。

public int jump(int[] nums) {
        if (nums.length <= 1)return 0;
        int i = 0, n = nums.length, lc = 0, ln = 0, step = 1;
        // lc means the longest distance can achieve by current jump
        // ln means the longest distance can achieve by next jump
        lc = nums[0];
        ln = nums[0]; // Initialize to index 0, the start point.
        for (i = 1; i < n; ++i) {
            if (i > lc){ // current jump cannot get index i -->>> must jump one more time.
                lc = ln;
                step++;
            }
            if (i + nums[i] > ln)ln = i + nums[i]; // maintain the furthest distance of next jump can get
            if (lc >= n - 1) return step;// current jump can achieve the last index
        }
        return step;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值