LeetCode—jump-game-ii(跳跃数组的步长,返回最小步数)——java

138 篇文章 0 订阅
132 篇文章 0 订阅

题目描述

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 is2. (Jump1step from index 0 to 1, then3steps to the last index.)

思路解析

  • 这个是在版本1的基础上,返回步数,从索引0开始,对应数组中的值就是最大的步数,返回最少走几步,就可以到达数组末尾
  • 所以lastcover表示在小于lastcover的位置到lastcover这段路途,走了maxcover即最大的步长。所以步数加1;所以这个时候需要更新lastcover的值
  • 只是原来的全局最优现在要分成step步最优和step-1步最优(假设当前步数是step)。当走到超过step-1步最远的位置时,说明step-1不能到达当前一步,我们就可以更新步数,将step+1。时间复杂度仍然是O(n),空间复杂度也是O(1)。参考https://blog.csdn.net/linhuanmars/article/details/21356187/

代码

public class Solution {
    public 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++;
                lastcover = maxcover;
            }
            if(A[i]+i>maxcover){
                maxcover = A[i]+i;
            } 
        }
        if(maxcover < A.length-1)
            return 0;
        return step;
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值