跳跃游戏

题目描述:给定一个非负整数数组,你最初位于数组的第一个位置。

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

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

题目地址:https://leetcode-cn.com/problems/jump-game/

思路:

1、如果数组里的数字都不为0那么肯定能到达最后一个位置,那么重点看为0的元素的之前元素能否跳过这个0元素,此时分为两种情况,一个是当前0元素在最后一个位置,那么可以直接返回true,一个是当前0元素在其它位置,那么往前循环,而且每循环一次需要多增加一步,满足条件即可跳过这个0元素,否则跳出循环。

2、设置maxPos为当前所能到达的最大位置,如果i在此范围类,则可以继续前进,如果能到达的位置大于maxPos则更新它的值,当i仍在循环且i大于maxPos时可以直接返回false;

代码展示:

1、

/**
 * @ClassName Solution
 * @Description
 * @Author Administrator
 * @Date 2020/6/8 11:42
 * @Version 1.0
 **/
class Solution {
    public boolean canJump(int[] nums) {
        if(nums == null)
            return false;
        if(nums.length == 1)
            return true;
        int i;
        for(i = 0; i < nums.length; i++){
            if(nums[i] == 0){
                int temp;
                if(i == nums.length - 1)
                    return true;
                else
                    temp = 2;
                int j;
                for(j = i - 1; j >= 0; j--, temp ++){
                    if(nums[j] >= temp)
                        break;
                }
                if(j == -1)
                    break;
            }
        }
        if(i < nums.length)
            return false;
        else
            return true;
    }
}

2、

/**
 * @ClassName Solution1
 * @Description
 * @Author Administrator
 * @Date 2020/6/8 12:05
 * @Version 1.0
 **/
public class Solution1 {
    public boolean canJump(int[] nums) {
        int maxPos = 0;
        for(int i = 0; i < nums.length; i++){
            if(i <= maxPos){
                if(nums[i] + i > maxPos)
                    maxPos = nums[i] + i;
            }
            else
                return false;
        }
        if(maxPos >= nums.length - 1)
            return true;
        else
            return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值