题解 | #跳跃游戏(三)#

跳跃游戏(三)

https://www.nowcoder.com/practice/14abdfaf0ec4419cbc722decc709938b

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param nums int整型一维数组
     * @return int整型
     */
    public int minJumpStep (int[] nums) {
        // write code here
        // 解题思路:
        //遍历数组,每次找到最大位置,如果最大位置小于下标,说明当前下标不可达
        // 在最大位置范围内,寻找下一跳的最大位置

        if (nums == null || nums.length == 0) {
            return -1;
        }

        int maxPosition = 0;
        int preMax = 0;
        int step = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            // 说明当前下标不可达
            if (i > maxPosition) {
                return -1;
            }

            maxPosition = Math.max(maxPosition, i + nums[i]);

            if (i == preMax) {
                preMax = maxPosition;
                step++;
            }
        }

        if (maxPosition < nums.length - 1) {
            return -1;
        }

        return step;
    }
}

全部评论

相关推荐

996的工作制还是没能硬啃下去,快要面试怂了,取消了
牛客80700350...:很正常,不是所有人都能接受这种强度的。不叫怯战,这叫明智
点赞 评论 收藏
分享
政委qqq:这道题在算法竞赛里唯一考的就是高精度,但是只能难住C++这类语言,Python直接a+b秒天秒地
点赞 评论 收藏
分享
温柔的小松鼠在刷题:太杂了,三个方向的东西,虽然有关联,但关联性不大
985本硕1个中小厂of...
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务