Java解决跳跃游戏1

Java解决跳跃游戏(贪心)

01 题目

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

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

    示例 1:

    输入:nums = [2,3,1,1,4]
    输出:true
    解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
    

    示例 2:

    输入:nums = [3,2,1,0,4]
    输出:false
    解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
    

    提示:

    • 1 <= nums.length <= 104
    • 0 <= nums[i] <= 105

02 知识点

  • 循环
  • 贪心

03 我的题解思路

public class canJump2 {
	public static void main(String[] args) {
//		测试数据
		int[] nums ={3,2,1,0,4};
		System.out.println(canJump(nums));
		
	}
	public static boolean canJump(int[] nums) {
		int num=nums.length;//数组长度
		int right=0;//当前所到最远索引
		for (int i = 0; i < num; i++) {
//			判断当前索引是否到可以抵达的最远索引
			if(i<=right) {
//				判断可抵达的最远索引是否增加
				right=Math.max(right, nums[i]+i);
//				如果最远索引大于数组索引,则返回成功
				if(right>=num-1) {
					return true;
				}
			}
		}
		return false;
    }
}


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是Java游戏推箱子实现跳跃功能的代码示例: ```java public class Player { // 玩家当前位置的坐标 private int x; private int y; // 玩家是否处于跳跃状态 private boolean isJumping; // 玩家跳跃的高度和跳跃的速度 private int jumpHeight; private int jumpSpeed; public Player(int x, int y) { this.x = x; this.y = y; this.isJumping = false; this.jumpHeight = 4; this.jumpSpeed = 2; } public void jump() { // 如果玩家已经处于跳跃状态,则不能重复跳跃 if (isJumping) { return; } isJumping = true; new Thread(new Runnable() { @Override public void run() { // 玩家跳跃的总高度 int totalHeight = jumpHeight * 2; // 玩家跳跃的当前高度 int currentHeight = 0; // 玩家跳跃的当前速度 int currentSpeed = jumpSpeed; while (currentHeight < totalHeight) { // 更新玩家位置 y -= currentSpeed; currentHeight += currentSpeed; // 等待一段时间再更新位置,实现跳跃的动画效果 try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } // 当玩家跳到最高点时,开始下落 if (currentHeight == jumpHeight) { currentSpeed = -jumpSpeed; } } // 玩家跳跃结束,恢复默认状态 isJumping = false; } }).start(); } } ``` 以上代码中,`Player`类表示游戏中的玩家,其中`x`和`y`表示玩家当前位置的坐标,`isJumping`表示玩家是否处于跳跃状态,`jumpHeight`表示玩家跳跃的高度,`jumpSpeed`表示玩家跳跃的速度。`jump()`方法实现了玩家跳跃的功能,通过新建一个线程来实现跳跃的动画效果。在跳跃时,玩家的位置会不断地更新,直到跳到最高点,然后开始下落,直到回到原来的位置。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宣布无人罪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值