LeetCode(55):跳跃游戏 Jump Game(Java)

本文是LeetCode从零单刷笔记,针对跳跃游戏这一题目给出解题思路。不能用暴力法,有从前往后和从后往前两种思路。从前往后更新最远可达距离,从后往前更新能到达尾部的位置,根据能否到达相应位置判断游戏是否通过。

2019.5.28 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

既然是智力题那肯定不能用暴力法,有两种思路:

1.从前往后

设定一个变量用来存储最远可达距离maxdist,从前往后每当走到每一个位置的时候,更新这个距离。如果maxdist能够到达最后一位,则游戏通过,返回true;如果不能到达,则游戏失败,返回false。

2.从后往前

设定一个标志位代表最后一位lastPos,从后往前每当一个新的位置能够到达尾部,则将lastPos更新至该位置。如果lastPos能够到达首位,则游戏通过,返回true;如果不能到达,则游戏失败,返回false。


传送门:跳跃游戏

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.

Determine if you are able to reach the last index.

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个位置。

示例 1:
输入: [2,3,1,1,4]
输出: true
解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。

示例 2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 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.
 * Determine if you are able to reach the last index.
 * 给定一个非负整数数组,你最初位于数组的第一个位置。
 * 数组中的每个元素代表你在该位置可以跳跃的最大长度。
 * 判断你是否能够到达最后一个位置。
 *
 */

public class JumpGame {

    // 设定一个变量用来存储最远可达距离maxdist,从前往后每当走到每一个位置的时候,更新这个距离。
    // 如果maxdist能够到达最后一位,则游戏通过,返回true;如果不能到达,则游戏失败,返回false。
    public boolean canJump(int[] nums) {
        int maxdist = 0;
        for(int i = 0; i <= maxdist; i++){
            int curdist = i + nums[i];
            if(curdist >= nums.length - 1) {
                return true;
            }
            maxdist = curdist > maxdist ? curdist : maxdist;
        }
        return false;
    }

    // 设定一个标志位代表最后一位lastPos,从后往前每当一个新的位置能够到达尾部,则将lastPos更新至该位置。
    // 如果lastPos能够到达首位,则游戏通过,返回true;如果不能到达,则游戏失败,返回false。
    public boolean canJump2(int[] nums) {
        int lastPos = nums.length - 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (i + nums[i] >= lastPos) {
                lastPos = i;
            }
        }
        return lastPos == 0;
    }
    
}



#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值