55. 跳跃游戏(Java)

题目描述:

给你一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个下标,如果可以,返回 true ;否则,返回 false 。

输入:

nums = 2,3,1,1,4

输出:

true

解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。

代码实现:

java 复制代码
public class Demo4 {
    public static void main(String[] args) {
        int[] nums = new int[]{2,3,1,1,4};
        System.out.println(canJump(nums));//true
    }

    public static boolean canJump(int[] nums) {
        //记录当前能够跳跃到的最大位置
        int max = 0;
        //遍历数组
        for (int i = 0; i < nums.length; i++) {
            //当max不小于i时,才让max更新一直最大跳跃长度
            if (max >= i) {
                //更新最大一跳
                max = Math.max(max, nums[i] + i);
                if (max >= nums.length - 1) {
                    //如果当前能够跳到最后一个元素的位置,直接返回true
                    return true;
                }
            }
        }
        return false;
    }
}
相关推荐
某不知名網友6 小时前
C++ 深浅拷贝:从默认拷贝到 Rule of Five
java·开发语言
青山木6 小时前
Hot 100 --- 划分字母区间
java·数据结构·算法·leetcode·贪心算法
Zzzzmo_6 小时前
SpringBoot 配置文件
java·spring boot
君顾17 小时前
外卖CPS小程序开发实战指南:从零到上线的完整流程
java·开发语言·外卖
無a伟7 小时前
RabbitMq高级特性:消息确认,持久化,重试机制
java·分布式·rabbitmq
Sunsets_Red7 小时前
浅谈扫描线
c++·算法·编程·题解·洛谷·扫描线·信息学竞赛
流烟默7 小时前
xxl-job 接入 Spring 的两种方式:手动装配与自动装配(含 initMethod 双启动踩坑实录)
java·spring·xxl-job
a187927218317 小时前
【算法】双指针与滑动窗口(一):框架总纲——三类问题、一个原理与判决书
算法·leetcode·区间·双指针·滑动窗口·原理·算法讲解
鹅城剑仙7 小时前
Spring Boot 3 全局异常处理与统一响应封装进阶实战
java·spring boot·后端
shehuiyuelaiyuehao7 小时前
算法42,模拟算法,模拟z字形变换
算法