leetcode canJump55

力扣

 

 

package leetcode;

public class canJump55 {
    public static void main(String[] args) {
        //int[] nums = {2,3,1,1,4};
        int[] nums = {1,1,2,2,0,1,1};
        //实现方案A
        System.out.println(canJump(nums));
    }
    public static boolean canJumpB(int[] nums) {
        int  hat = 0 ;
        int j = nums.length-1;
        for (int i = 0; i < nums.length; i++) {
            //找出当前步向前跳范围内,能跳的最远的下标
            int a = i+nums[i];
             if(a>hat){
                 hat = a;
             }
            if(hat>=j){
                return true;
            }
            if (hat <= i) {
                return false;
            }
        }
        return false;
    }

    /**
     * 从数组第一位调到最后一位
     * 数组里的数是向前可以跳的步数
     * @param nums
     * @return
     */
    public static boolean canJump(int[] nums) {
        int tag = 0 ;
        for (int i = 0; i < nums.length; i++) {
            //找出当前步向前跳范围内,能跳的最远的下标
            tag = getTag(tag,nums);
            if (tag == -1) {
                return false;
            }
            if (tag == nums.length-1) {
                return true;
            }
        }
        return false;

    }

    private static int getTag(int tag, int[] nums) {
        //如果能直接跳到终点 就直接返回中点
        if (nums[tag] >= nums.length-1-tag) {
            return nums.length-1;
        }
        //如果跳的最远的为0 说明跳不了了 直接返回-1表示
        if (nums[tag]==0) {
            return -1;
        }
        //如果是一个就直接返回不用比较
        if (nums[tag]==1) {
            return tag+1;
        }
        int max =tag+1;
        //判断范围内能跳的最远的下一个
        for (int i = tag+2; i <= tag+nums[tag]; i++) {
            //比较出个最大的
            if (nums[max] < nums[i] + (i-max)) {
                max = i;
            }
        }
        return max;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值